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)

PDF
Apache jMeter
NexThoughts Technologies
 
PDF
Testing Angular
Lilia Sfaxi
 
PDF
Introduction to Robot Framework
Somkiat Puisungnoen
 
PPTX
Test automation within a scrum process
Kushan Shalindra Amarasiri - Technical QE Specialist
 
PPTX
Angular Unit Testing
Shailendra Chauhan
 
PDF
The Many Ways to Test Your React App
All Things Open
 
PDF
Unit Testing in Angular
Knoldus Inc.
 
PPTX
Introduction to .NET Core
Marco Parenzan
 
PPTX
Cypress Automation
Susantha Pathirana
 
PPTX
TestNG Framework
Levon Apreyan
 
PDF
TypeScript Best Practices
felixbillon
 
PDF
JUnit 5 - The Next Generation
Kostadin Golev
 
PPTX
Unit Testing Concepts and Best Practices
Derek Smith
 
PPT
Test Automation Best Practices (with SOA test approach)
Leonard Fingerman
 
PDF
Jmeter Performance Testing
Atul Pant
 
PDF
Automated testing with Cypress
Yong Shean Chong
 
PDF
Playwright: A New Test Automation Framework for the Modern Web
Applitools
 
PPT
Test Automation Strategies For Agile
Naresh Jain
 
PDF
TypeScript - An Introduction
NexThoughts Technologies
 
PDF
Angular and The Case for RxJS
Sandi Barr
 
Testing Angular
Lilia Sfaxi
 
Introduction to Robot Framework
Somkiat Puisungnoen
 
Test automation within a scrum process
Kushan Shalindra Amarasiri - Technical QE Specialist
 
Angular Unit Testing
Shailendra Chauhan
 
The Many Ways to Test Your React App
All Things Open
 
Unit Testing in Angular
Knoldus Inc.
 
Introduction to .NET Core
Marco Parenzan
 
Cypress Automation
Susantha Pathirana
 
TestNG Framework
Levon Apreyan
 
TypeScript Best Practices
felixbillon
 
JUnit 5 - The Next Generation
Kostadin Golev
 
Unit Testing Concepts and Best Practices
Derek Smith
 
Test Automation Best Practices (with SOA test approach)
Leonard Fingerman
 
Jmeter Performance Testing
Atul Pant
 
Automated testing with Cypress
Yong Shean Chong
 
Playwright: A New Test Automation Framework for the Modern Web
Applitools
 
Test Automation Strategies For Agile
Naresh Jain
 
TypeScript - An Introduction
NexThoughts Technologies
 
Angular and The Case for RxJS
Sandi Barr
 

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)

PPTX
Security testing of YUI powered applications
dimisec
 
PPTX
A few good JavaScript development tools
Simon Kim
 
PDF
Test driven node.js
Jay Harris
 
PDF
Testing in JavaScript
Digital Natives
 
PDF
node.js Module Development
Jay Harris
 
PPTX
Understanding JavaScript Testing
Kissy Team
 
PDF
Browser testing with nightwatch.js - Drupal Europe
Salvador Molina (Slv_)
 
PDF
Тестирование и Django
MoscowDjango
 
PDF
Continuous Integration for front-end JavaScript
Lars Thorup
 
ZIP
Browser-Based testing using Selenium
ret0
 
PDF
Node.js vs Play Framework (with Japanese subtitles)
Yevgeniy Brikman
 
PDF
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
GreeceJS
 
PDF
Artem Yavorsky "99 ways to take away your ugly polyfills"
Fwdays
 
PPTX
Beyond DOMReady: Ultra High-Performance Javascript
aglemann
 
PDF
Zero-config JavaScript apps with RaveJS -- SVCC fall 2014
John Hann
 
PDF
Node intro
cloudhead
 
PDF
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
Enterprise PHP Center
 
PDF
Reliable Javascript
Glenn Stovall
 
PPT
JavaScript Unit Testing
Christian Johansen
 
PDF
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Security testing of YUI powered applications
dimisec
 
A few good JavaScript development tools
Simon Kim
 
Test driven node.js
Jay Harris
 
Testing in JavaScript
Digital Natives
 
node.js Module Development
Jay Harris
 
Understanding JavaScript Testing
Kissy Team
 
Browser testing with nightwatch.js - Drupal Europe
Salvador Molina (Slv_)
 
Тестирование и Django
MoscowDjango
 
Continuous Integration for front-end JavaScript
Lars Thorup
 
Browser-Based testing using Selenium
ret0
 
Node.js vs Play Framework (with Japanese subtitles)
Yevgeniy Brikman
 
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
GreeceJS
 
Artem Yavorsky "99 ways to take away your ugly polyfills"
Fwdays
 
Beyond DOMReady: Ultra High-Performance Javascript
aglemann
 
Zero-config JavaScript apps with RaveJS -- SVCC fall 2014
John Hann
 
Node intro
cloudhead
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
Enterprise PHP Center
 
Reliable Javascript
Glenn Stovall
 
JavaScript Unit Testing
Christian Johansen
 
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Ad

Recently uploaded (20)

PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 

Painless JavaScript Testing with Jest