SlideShare a Scribd company logo
Michał Pierzchała
🃏 Painless JavaScript Testing
About me
xfive.co jest-core@thymikee
Reintroducing
Jest
🃏 Painless JavaScript Testing
🃏 Jest
🃏 Jest
You’ve probably heard
about it centuries* ago
* in WST – Web Standard Time
🃏 Jest
0
15
30
45
60
2014 VII 2015 I 2016 VI 2016 I 2017
Awesomeness
meh
not bad nice!
🃏 Jest
Painless, right?
🃏 Jest
“Simple things should be simple,
complex things should be possible”
~ Alan Kay
🃏 Jest
Complete
Testing Platform
easy to setup
configurable
familiar syntax
babel-friendly
meaningful error messages
smart watch-mode
fast
efficient
testing DOM
snapshot testing
sandboxed & parallel tests
built-in coverage
built-in mocking
async tests
compile-to-JS-friendly
🃏 Jest
"
Easy to setup
🃏 Jest
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
$ npm i -D jest
🃏 Jest
├── __tests__
│ └── component.spec.js
│ └── anything.js
├── package.json
├── foo.test.js
├── bar.spec.js
└── component.js
will treat these files as tests:
🃏 Jest
🃏 Jest
Familiar syntax
Jest uses Jasmine as a test runner
but it does so much more around it
🃏 Jest
// some.test.js
beforeEach(runBefore);
afterAll(runAfterAll);
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
expect(object).not.toBeTruthy();
});
🃏 Jest
Convenient test
status reporter
🃏 Jest
🃏 Jest
Configurable
🃏 Jest
// package.json
"jest": {
"testEnvironment": "node",
"setupFiles": [
"<rootDir>/setup.js"
],
"testRegex": ".*-test.js",
...
}
🃏 Jest
Babel-friendly
Jest reads your .babelrc
and package.json
🃏 Jest
// .babelrc
{
"presets": ["es2015", "react"]
}
$ npm i -D babel-jest
NODE_ENV = "test"
🃏 Jest
Works with any
compile-to-JS language
TypeScript for example!
🃏 Jest
"jest": {
"transform": {
".*tsx?$": "<rootDir>/ts-preprocessor.js"
},
"testRegex": ".*.test.(tsx?|jsx?)$”,
"moduleFileExtensions": ["ts", "tsx", "js"]
}
🃏 Jest
🃏
CUTENESS
BREAK
🃏 Jest
Testing DOM
Jest uses jsdom to fake it
🃏 Jest
const $ = require('jquery');
const handleButtonClick =
require('../handleButtonClick');
it('displays a user after a click', () => {
document.body.innerHTML =
'<button id="button" />';
handleButtonClick();
$('#button').click();
expect($('#button').text())
.toEqual('Button Clicked!');
});
🃏 Jest
Async tests
🃏 Jest
const user = require('./user');
test('works with async/await', async () => {
const name = await user.getUserName(42);
expect(name).toEqual('Arnold');
});
use async/await
🃏 Jest
const user = require('./user');
test('works with async/await', () => {
return user.getUserName(42).then(name => {
expect(name).toEqual('Arnold')
});
});
or return a Promise
🃏 Jest
const user = require('./user');
test('works with async/await', (done) => {
user.getUserName(42).then(name => {
expect(name).toEqual('Arnold');
done();
}).catch(done.fail);
});
or call done() / done.fail()
🃏 Jest
📸
Snapshot tests
Literally saving a snapshot of any serialisable value
e.g. a React component
🃏 Jest
import React from 'react';
import Header from '../Header';
import renderer from 'react-test-renderer';
test('renders header', () => {
const component = renderer.create(
<Header title="Hello, world!" />
);
expect(component).toMatchSnapshot();
});
🃏 Jest
exports[`test renders header 1`] = `
<header>
<h1>
Hello, world!
</h1>
</header>
`;
saves a file in sibling __snapshots__ directory:
🃏 Jest
🃏 Jest
• React & ReactNative components
• Objects shape (e.g. Redux)
• CLI output
• Changes in time
• GraphQL queries
• DB shape (e.g. Mongoose)
• so much more…
snapshots are great for testing:
🃏 Jest
• user attention while updating/validating is required
• one must be sure that snapshot output is valid
• updating particular snapshots is not super convenient (yet)
but be aware of pitfalls
🃏 Jest
use responsibly
🃏 Jest
Fast & efficient
Jest runs tests in parallel on all available cores
Caches test results and babel transforms
Runs errored tests first.
🃏 Jest
Sandboxed
each test has its own virtual environment
🃏 Jest
These test suites run
in parallel sandboxes
🃏 Jest
Meaningful Error
Messages
🃏 Jest
🃏 Jest
Built-in coverage reporter
🃏 Jest
$ jest --coverage
🃏 Jest
Built-in mocking
Jest features so called
manual mocks and a mocking functions
🃏 Jest
manual mocks
reside in __mocks__ directory
├── __mocks__
│ └── fs.js
├── __tests__
├── models
│ └── __mocks__
│ └──── user.js
│ └── user.js
└── component.js
🃏 Jest
sample implementation of __mocks__/request.js
'use strict';
const users = {
4: {name: 'Pablo'},
};
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(
url.substr('/users/'.length), 10
);
process.nextTick(
() => users[userID]
? resolve(users[userID])
: reject({error: `${userID} not found`})
);
});
}
🃏 Jest
substitute all calls to request
from any module
with implementation from __mocks__
jest.mock('../request');
🃏 Jest
jest.mock can also be implemented in-place
jest.mock('any-module', () => 42);
jest.mock('fake', () => false, {virtual: true});
🃏 Jest
mock functions with jest.fn()
test('mocks', () => {
const mockFn = jest.fn(() => 1337);
const test = new mockFn(); // first call
expect(mockFn).toHaveBeenCalled();
mockFn('first arg', 'second arg’); // second call
expect(mockFn.mock.calls[1][0]).toBe('first arg');
expect(mockFn.mock.calls[1][1]).toBe('second arg');
expect(mockFn.mock.instances.length).toBe(2);
expect(mockFn.mock.instances[0]).toEqual(test);
expect(mockFn()).toBe(1337);
});
🃏 Jest
Built-in matchers library
and they are extendable
🃏 Jest
• ongoing efforts for full compatibility with
popular expect package
• asymmetric matchers (adapted from Jasmine)
• mocks and spies
• expect.extend() API
🃏 Jest
Behold
watch mode
😵
🃏 Jest
• fast 🚀 (even faster in v19)
• can run tests related to changed files
(git & mercurial)
• pattern mode
• interrupting
• TDD-friendly
🃏 Jest
🃏 Jest
🃏 Jest
Editor integrations
🃏 Jest
vscode-jest by @orta
🃏 Jest
atom-jest in the making by @kentaromiura
🃏 Jest
I think I covered
most of the features
but there’s so much more! ✨
🃏 Jest
Want to try Jest now?
https://repl.it/languages/jest
🃏 Jest
Migrating to Jest?
$ npm i -g jest-codemods
Jasmine, Mocha, AVA, chai and Tape covered
🃏 Jest
Thank you.

More Related Content

What's hot (20)

PPTX
JMeter Intro
Sam Varadarajan
 
PPTX
Moq Presentation
LynxStar
 
PDF
Selenium IDE LOCATORS
Mindfire Solutions
 
PDF
JUnit 5
Scott Leberknight
 
PPTX
Unit Testing Concepts and Best Practices
Derek Smith
 
PPT
testng
harithakannan
 
PDF
Selenium with Cucumber
Knoldus Inc.
 
PDF
Socket.IO
Davide Pedranz
 
DOCX
Window Desktop Application Testing
Trupti Jethva
 
PPTX
Appium Presentation
OmarUsman6
 
PDF
Mocking in Java with Mockito
Richard Paul
 
PPSX
Microservices Testing Strategies JUnit Cucumber Mockito Pact
Araf Karsh Hamid
 
PPTX
Spring Security 5
Jesus Perez Franco
 
PDF
JUnit & Mockito, first steps
Renato Primavera
 
PDF
Clean Unit Test Patterns
Frank Appel
 
PPTX
Cucumber BDD
Pravin Dsilva
 
PDF
How to go about testing in React?
Lisa Gagarina
 
ODP
Test Automation Framework using Cucumber BDD overview (part 1)
Mindfire Solutions
 
PDF
e2e testing with cypress
Tomasz Bak
 
PDF
Browser_Stack_Intro
Mithilesh Singh
 
JMeter Intro
Sam Varadarajan
 
Moq Presentation
LynxStar
 
Selenium IDE LOCATORS
Mindfire Solutions
 
Unit Testing Concepts and Best Practices
Derek Smith
 
Selenium with Cucumber
Knoldus Inc.
 
Socket.IO
Davide Pedranz
 
Window Desktop Application Testing
Trupti Jethva
 
Appium Presentation
OmarUsman6
 
Mocking in Java with Mockito
Richard Paul
 
Microservices Testing Strategies JUnit Cucumber Mockito Pact
Araf Karsh Hamid
 
Spring Security 5
Jesus Perez Franco
 
JUnit & Mockito, first steps
Renato Primavera
 
Clean Unit Test Patterns
Frank Appel
 
Cucumber BDD
Pravin Dsilva
 
How to go about testing in React?
Lisa Gagarina
 
Test Automation Framework using Cucumber BDD overview (part 1)
Mindfire Solutions
 
e2e testing with cypress
Tomasz Bak
 
Browser_Stack_Intro
Mithilesh Singh
 

Viewers also liked (20)

PDF
Scalable CSS Architecture
Michał Pierzchała
 
PDF
Isomorphic React Apps Testing
Mikhail Larchanka
 
PDF
Unit Testing Lightning Components with Jasmine
Keir Bowden
 
PPTX
JavaScript Unit Testing
Keir Bowden
 
PDF
Testing javascript in the frontend
Frederic CABASSUT
 
PDF
Developer Experience to Testing
Mozaic Works
 
PDF
The Developer Experience
Atlassian
 
PDF
Introducing Sencha Touch 2
Sencha
 
PDF
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
PDF
Javascript testing: tools of the trade
Juanma Orta
 
PPTX
Javascript Testing with Jasmine 101
Roy Yu
 
DOCX
Atividade3FernandoLucioSoaresRamos
FLSR1
 
PDF
Javascript Unit Testing Tools
PixelCrayons
 
PDF
JAVASCRIPT Test Driven Development & Jasmine
Anup Singh
 
PDF
Unit-testing and E2E testing in JS
Michael Haberman
 
PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
PPTX
SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...
Sencha
 
PDF
A tour of React Native
Tadeu Zagallo
 
PPTX
jasmine
Asanka Indrajith
 
PPTX
React and Flux life cycle with JSX, React Router and Jest Unit Testing
Eswara Kumar Palakollu
 
Scalable CSS Architecture
Michał Pierzchała
 
Isomorphic React Apps Testing
Mikhail Larchanka
 
Unit Testing Lightning Components with Jasmine
Keir Bowden
 
JavaScript Unit Testing
Keir Bowden
 
Testing javascript in the frontend
Frederic CABASSUT
 
Developer Experience to Testing
Mozaic Works
 
The Developer Experience
Atlassian
 
Introducing Sencha Touch 2
Sencha
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Gavin Pickin
 
Javascript testing: tools of the trade
Juanma Orta
 
Javascript Testing with Jasmine 101
Roy Yu
 
Atividade3FernandoLucioSoaresRamos
FLSR1
 
Javascript Unit Testing Tools
PixelCrayons
 
JAVASCRIPT Test Driven Development & Jasmine
Anup Singh
 
Unit-testing and E2E testing in JS
Michael Haberman
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...
Sencha
 
A tour of React Native
Tadeu Zagallo
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
Eswara Kumar Palakollu
 
Ad

Similar to Painless JavaScript Testing with Jest (20)

PDF
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Holger Grosse-Plankermann
 
PDF
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
PDF
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
PPTX
Saving Time by Testing with Jest
All Things Open
 
PDF
The Many Ways to Test Your React App
All Things Open
 
PDF
An Introduction to the World of Testing for Front-End Developers
FITC
 
PDF
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
PDF
Front end testing you won't hate
Will Mitchell
 
PPTX
Testing React Applications
stbaechler
 
PPTX
MelbJS Nov2014 - CommonJS & Mocking with Jest
James Hunter
 
PDF
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
PPTX
Frontend training
Adrian Caetano
 
PPTX
unit test in node js - test cases in node
Goa App
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
PDF
Testing in FrontEnd World by Nikita Galkin
Sigma Software
 
PDF
An existential guide to testing React UIs
Emily Bookstein
 
PDF
Unit Testing your React / Redux app (@BucharestJS)
Alin Pandichi
 
PDF
Fernando Daciuk - The magic world of tests with Jest
React Conf Brasil
 
PPTX
Testing nodejs apps
felipefsilva
 
PPTX
Nevermore Unit Testing
Ihsan Fauzi Rahman
 
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Holger Grosse-Plankermann
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Holger Grosse-Plankermann
 
Saving Time by Testing with Jest
All Things Open
 
The Many Ways to Test Your React App
All Things Open
 
An Introduction to the World of Testing for Front-End Developers
FITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Haris Mahmood
 
Front end testing you won't hate
Will Mitchell
 
Testing React Applications
stbaechler
 
MelbJS Nov2014 - CommonJS & Mocking with Jest
James Hunter
 
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
GeeksLab Odessa
 
Frontend training
Adrian Caetano
 
unit test in node js - test cases in node
Goa App
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Testing in FrontEnd World by Nikita Galkin
Sigma Software
 
An existential guide to testing React UIs
Emily Bookstein
 
Unit Testing your React / Redux app (@BucharestJS)
Alin Pandichi
 
Fernando Daciuk - The magic world of tests with Jest
React Conf Brasil
 
Testing nodejs apps
felipefsilva
 
Nevermore Unit Testing
Ihsan Fauzi Rahman
 
Ad

Recently uploaded (20)

PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
Tally software_Introduction_Presentation
AditiBansal54083
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Import Data Form Excel to Tally Services
Tally xperts
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Executive Business Intelligence Dashboards
vandeslie24
 

Painless JavaScript Testing with Jest