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

PPTX
Testing of React JS app
PDF
Unit Testing in Angular
PDF
Unit Testing with Jest
PDF
How to go about testing in React?
PDF
Introduction to jest
PPTX
Saving Time By Testing With Jest
PPTX
Automation - web testing with selenium
PPTX
Jenkins tutorial for beginners
Testing of React JS app
Unit Testing in Angular
Unit Testing with Jest
How to go about testing in React?
Introduction to jest
Saving Time By Testing With Jest
Automation - web testing with selenium
Jenkins tutorial for beginners

What's hot (20)

ODP
BDD with Cucumber
PPTX
Jenkins CI
PDF
Cucumber ppt
PDF
Test and Behaviour Driven Development (TDD/BDD)
PDF
Jenkins tutorial
ODP
An Introduction To Jenkins
PPTX
Typescript in 30mins
PPS
JUnit Presentation
PDF
Jenkins 101: Getting Started
PDF
PDF
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
PPTX
Jenkins CI presentation
PPTX
UNIT TESTING PPT
PDF
SELENIUM PPT.pdf
PPTX
Introduction to Maven
PPT
Jenkins Overview
PPTX
JUnit- A Unit Testing Framework
PPT
TypeScript Presentation
BDD with Cucumber
Jenkins CI
Cucumber ppt
Test and Behaviour Driven Development (TDD/BDD)
Jenkins tutorial
An Introduction To Jenkins
Typescript in 30mins
JUnit Presentation
Jenkins 101: Getting Started
What is Jenkins | Jenkins Tutorial for Beginners | Edureka
Jenkins CI presentation
UNIT TESTING PPT
SELENIUM PPT.pdf
Introduction to Maven
Jenkins Overview
JUnit- A Unit Testing Framework
TypeScript Presentation
Ad

Viewers also liked (20)

PDF
Scalable CSS Architecture
PDF
Isomorphic React Apps Testing
PDF
Unit Testing Lightning Components with Jasmine
PPTX
JavaScript Unit Testing
PDF
Testing javascript in the frontend
PDF
Developer Experience to Testing
PDF
The Developer Experience
PDF
Introducing Sencha Touch 2
PDF
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
PDF
Javascript testing: tools of the trade
PPTX
Javascript Testing with Jasmine 101
DOCX
Atividade3FernandoLucioSoaresRamos
PDF
Javascript Unit Testing Tools
PDF
JAVASCRIPT Test Driven Development & Jasmine
PDF
Unit-testing and E2E testing in JS
PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
PPTX
SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...
PDF
A tour of React Native
PPTX
PPTX
React and Flux life cycle with JSX, React Router and Jest Unit Testing
Scalable CSS Architecture
Isomorphic React Apps Testing
Unit Testing Lightning Components with Jasmine
JavaScript Unit Testing
Testing javascript in the frontend
Developer Experience to Testing
The Developer Experience
Introducing Sencha Touch 2
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
Javascript testing: tools of the trade
Javascript Testing with Jasmine 101
Atividade3FernandoLucioSoaresRamos
Javascript Unit Testing Tools
JAVASCRIPT Test Driven Development & Jasmine
Unit-testing and E2E testing in JS
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...
A tour of React Native
React and Flux life cycle with JSX, React Router and Jest Unit Testing
Ad

Similar to Painless JavaScript Testing with Jest (20)

PDF
Das Frontend richtig Testen – mit Jest @Developer Week 2018
PDF
Jest: Frontend Testing richtig gemacht @WebworkerNRW
PDF
Jest: Frontend Testing leicht gemacht @EnterJS2018
PPTX
Saving Time by Testing with Jest
PDF
The Many Ways to Test Your React App
PDF
An Introduction to the World of Testing for Front-End Developers
PDF
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
PDF
Front end testing you won't hate
PPTX
Testing React Applications
PPTX
MelbJS Nov2014 - CommonJS & Mocking with Jest
PDF
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
PPTX
Frontend training
PPTX
unit test in node js - test cases in node
PDF
Workshop 23: ReactJS, React & Redux testing
PDF
Testing in FrontEnd World by Nikita Galkin
PDF
An existential guide to testing React UIs
PDF
Unit Testing your React / Redux app (@BucharestJS)
PDF
Fernando Daciuk - The magic world of tests with Jest
PPTX
Testing nodejs apps
PPTX
Nevermore Unit Testing
Das Frontend richtig Testen – mit Jest @Developer Week 2018
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing leicht gemacht @EnterJS2018
Saving Time by Testing with Jest
The Many Ways to Test Your React App
An Introduction to the World of Testing for Front-End Developers
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
Front end testing you won't hate
Testing React Applications
MelbJS Nov2014 - CommonJS & Mocking with Jest
JS Lab`16. Сергей Селецкий: "Ретроспектива тестирования JavaScript"
Frontend training
unit test in node js - test cases in node
Workshop 23: ReactJS, React & Redux testing
Testing in FrontEnd World by Nikita Galkin
An existential guide to testing React UIs
Unit Testing your React / Redux app (@BucharestJS)
Fernando Daciuk - The magic world of tests with Jest
Testing nodejs apps
Nevermore Unit Testing

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
System and Network Administration Chapter 2
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
System and Network Administraation Chapter 3
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
history of c programming in notes for students .pptx
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Digital Systems & Binary Numbers (comprehensive )
PPTX
Introduction to Artificial Intelligence
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Operating system designcfffgfgggggggvggggggggg
How to Choose the Right IT Partner for Your Business in Malaysia
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
System and Network Administration Chapter 2
wealthsignaloriginal-com-DS-text-... (1).pdf
System and Network Administraation Chapter 3
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Understanding Forklifts - TECH EHS Solution
Design an Analysis of Algorithms I-SECS-1021-03
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
history of c programming in notes for students .pptx
Which alternative to Crystal Reports is best for small or large businesses.pdf
Digital Systems & Binary Numbers (comprehensive )
Introduction to Artificial Intelligence
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Computer Software and OS of computer science of grade 11.pptx
2025 Textile ERP Trends: SAP, Odoo & Oracle
Wondershare Filmora 15 Crack With Activation Key [2025
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)

Painless JavaScript Testing with Jest