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
Use Promise
  • Be sure to return the Promise
Use .resolves, .rejects
  • Waits until the Promise reolves
Use async, await

Setup and Teardown

Mock Functions

Using a mock function
Mock Return Values
Mocking Modules
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();
});
  1. When the first time the test is run, Jest creates a snapshot file.
  2. After that, Jest compares new caculated results with it.
  3. To update it, run following command:

    jest --updateSnapshot 
    

API Reference

Globals

test(name, fn, timeout)
  • Alias it(name, fn, timeout)

Configuring Jest

package.json
jest.config.js
With --config option
  • MUST not contain jest key in json
setupFiles [array]
  • The paths to modules that run some code to configure or set up the testing environment before each test.
testMatch [array]