Jest
Table of Contents
Introduction
Using Matchers
expect(x).toBeNull();
expect(x).toBeDefined();
expect(x).not.toBeUndefined();
expect(x).not.toBeTruthy();
expect(x).toBeFalsy();
expect(x).toBeGreaterThan(3);
expect(x).toBeGreaterThanOrEqual(3.5);
expect(x).toBeLessThan(5);
expect(x).toBeLessThanOrEqual(4.5);
expect(x).toBe(4);
expect(x).toEqual(4);
expect(x).toBeCloseTo(0.3);
expect(x).toMatch(/stop/);
expect(x).toContain('beer');
expect(x).toThrow();
expect(mockFunc).toBeCalled();
expect(mockFunc).toBeCalledWith(arg1, arg2);
expect(mockFunc).lastCalledWith(arg1, arg2);
expect(mockFunc).toMatchSnapshot();
Testing Asynchronous Code
- Use
done
- Be sure to call
done
- Be sure to call
- Use
Promise
- Be sure to return the
Promise
- Be sure to return the
- Use
.resolves
,.rejects
- Waits until the
Promise
reolves
- Waits until the
- Use
async
,await
Setup and Teardown
- Like tests, setup and teardown functions can also be used with
done
param or returningPromise
. beforeAll
,afterAll
are scoped withgiin the file they are placed inUse
beforeEach
,afterEach
::Use
beforeAll
,afterAll
::- Use
describe
for scoping ::- Jest executes all
describe
handlers in a test file before it executes any of the actual tests.
describe('matching cities to foods', () => { // Applies only to tests in this describe block beforeEach(() => { return initializeFoodDatabase(); }); test('Vienna <3 sausage', () => { expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true); }); test('San Juan <3 plantains', () => { expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true); }); });
beforeAll(() => console.log('1 - beforeAll')); afterAll(() => console.log('1 - afterAll')); beforeEach(() => console.log('1 - beforeEach')); afterEach(() => console.log('1 - afterEach')); test('', () => console.log('1 - test')); describe('Scoped / Nested block', () => { beforeAll(() => console.log('2 - beforeAll')); afterAll(() => console.log('2 - afterAll')); beforeEach(() => console.log('2 - beforeEach')); afterEach(() => console.log('2 - afterEach')); test('', () => console.log('2 - test')); });
1 - beforeAll 1 - beforeEach 1 - test 1 - afterEach 2 - beforeAll 1 - beforeEach 2 - beforeEach 2 - test 2 - afterEach 1 - afterEach 2 - afterAll 1 - afterAll
- Jest executes all
Mock Functions
- Using a mock function
function forEach(items, callback) { for (let index = 0; index < items.length; index++) { callback(items[index]); } }
const mockCallback = jest.fn(); forEach([0, 1], mockCallback); // The mock function is called twice expect(mockCallback.mock.calls.length).toBe(2); // The first argument of the first call to the function was 0 expect(mockCallback.mock.calls[0][0]).toBe(0); // The first argument of the second call to the function was 1 expect(mockCallback.mock.calls[1][0]).toBe(1);
- Mock Return Values
- Mocking Modules
// users.test.js import axios from 'axios'; import Users from './users'; jest.mock('axios'); test('should fetch users', () => { const resp = {data: [{name: 'Bob'}]}; axios.get.mockResolvedValue(resp); // or you could use the follwing depending on your use case: // axios.get.mockImplementation(() => Promise.resolve(resp)) return Users.all().then(users => expect(users).toEqual(resp.data)); });
- Mock Implementations
- Mock Names
- Give a name to the mock function for error output.
Jest Platform
Jest Community
More Resources
Guides
Snapshot Testing
Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.
import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer
.create(<Link page="http://www.facebook.com">Facebook</Link>)
.toJSON();
expect(tree).toMatchSnapshot();
});
- When the first time the test is run, Jest creates a snapshot file.
- After that, Jest compares new caculated results with it.
To update it, run following command:
jest --updateSnapshot
- Snapshot files should be committed.
- The aim of snapshot testing is not to replace existing unit tests, but providing additional value and making testing painless.
- Snapshots help figuring out whether the output of the modules covered by tests is changed, rather than giving guidance to design the code in the first place.
API Reference
Globals
test(name, fn, timeout)
- Alias
it(name, fn, timeout)
- Alias
Configuring Jest
package.json
jest.config.js
- With
--config
option - MUST not contain
jest
key in json
- MUST not contain
- setupFiles
[array]
- The paths to modules that run some code to configure or set up the testing environment before each test.
- testMatch
[array]
default (uses micromatch patterns)