Skip to main content
Quick Reference

Jest Cheatsheet

Jest on one page — matchers, mocks, fake timers, and the traps around toBe, awaits, and spy restore.

10 sections 10 tables 14 code snippets

A test

Actual, then the expected value

test("adds", () => {
  expect(add(2, 2)).toBe(4);
});

What runs

PieceMeaning
testOne case. it is the same function
expectWraps a value. A matcher such as toBe decides pass or fail
describeA group. It is not a test by itself
This fileTests in one file run in order, in one worker
Other filesJest may run other files at the same time, in other workers
TimeoutA test defaults to 5 seconds. The third argument to test raises that limit

This page is the Jest runner. React Testing Library and browser end-to-end tools are left out.

Matchers

Same fields, different object

expect(cart).toEqual({ items: 1 });

Identity

# toBe uses Object.is

Which comparison

MatcherCompares
toBeObject.is. Right for a primitive, or for the same object reference
toEqualDeep values. Ignores a key whose value is undefined, a hole in an array, and the class of an object
toStrictEqualAlso checks undefined keys, array holes, and the object type
toBeCloseToFloats. 0.2 + 0.1 versus 0.3 fails toBe
toContainA substring, or an array item compared with ===
toContainEqualAn array item compared field by field

Thrown errors

Pass a function, do not call it

expect(() => parse("")).toThrow(TypeError);

What the argument means

ArgumentPasses when
NoneThe function throws anything
StringThe message contains that substring
RegexThe message matches
ClassThe thrown value is an instance of that class
Error objectThe message equals that error message
Called yourselfThe throw escapes before toThrow can catch it

Promises

Wait for the matcher

await expect(load()).resolves.toBe("ok");

How a promise is asserted

FormRequired
async testAwait the promise, then assert the value
resolvesUnwraps a fulfilled promise. Return the expectation, or await it
rejectsThe promise rejects. Chain toThrow for the error
Forgotten awaitThe test can finish before the matcher runs
expect.assertions(n)Fails when fewer matchers ran, so a skipped branch cannot pass quietly
doneThe callback style. Prefer async. Mixing done with a returned promise uses two endings

Mocks

A fake that records calls

const fetchUser = jest.fn().mockResolvedValue({ id: 1 });

Wrap a real method

jest.spyOn(mail, "send").mockReturnValue(true);

What each stand-in does

CallEffect
jest.fn()Records calls and can return a fake value
mockReturnValueEvery call returns that value
mockResolvedValueEvery call returns a promise of that value
spyOnWraps an existing method and still calls the original, until you replace it
toHaveBeenCalledWithPasses when any recorded call matches those arguments, using toEqual
jest.mockReplaces a module for this file only. With babel-jest the call is hoisted above the imports

Between tests

Drop the call history

jest.clearAllMocks();

Spies only

# restoreAllMocks undoes spyOn

Clear, reset, restore

CallWhat it clears
clearAllMocksCall history, instances, and results. The fake implementation stays
resetAllMocksHistory, and the fake implementation. A reset spy returns undefined
restoreAllMocksPuts the original back for spyOn and replaceProperty only
A jest.fn you maderestoreAllMocks does not remove it. Clear or reset that function yourself
Another fileA jest.mock here does not mock the module for a different test file
Module stateA top-level import runs once. jest.resetModules() plus a fresh require reloads it

Fake timers

Move the clock

jest.useFakeTimers();
jest.advanceTimersByTime(1000);

The fake clock

CallEffect
useFakeTimersSwaps Date, setTimeout, setInterval, and the other timer APIs
ScopeLasts for the rest of this file, until useRealTimers
advanceTimersByTimeMoves the clock by that many milliseconds and runs timers that are due
runAllTimersRuns pending timers. Stops after 100,000 recursive timers by default
nextTickIn Node, process.nextTick is faked too
Real waitWithout fake timers, a one-second timeout waits on the real clock and can hit the 5 second limit

Many rows

One title, one row

test.each([[1, 1, 2]])("%i + %i", (a, b, sum) => {
  expect(a + b).toBe(sum);
});

Tables and filters

FormMeaning
test.eachOne test per row. The title can use %i and %s
RowsAn array of arrays. Each inner array is the arguments for one run
describe.eachThe same idea for a whole group
test.onlyRuns that test and leaves the others in the file unrun
test.skipReports the test as skipped
OrderRows run in the order written, inside this file

Hooks

A clean list before each test

beforeEach(() => {
  cart = [];
});

Scope

HookWhen
beforeEachBefore each test in this describe, after any outer beforeEach
afterEachAfter each test in this describe. The inner hook runs first
beforeAllOnce, before the tests in this describe
afterAllOnce, after those tests
A let you resetStarts clean when beforeEach assigns it. A module array you push into does not
Fake timers left onuseFakeTimers is file-wide. A later test still sees the fake clock

Interview traps

Await the assertion

# return expect(load()).resolves.toBe("ok")

The factory is hoisted

# jest.mock runs above the imports

Traps worth memorising

TrapWhat happensPrefer
toBe on two objectsObject.is is false for two objects with the same fieldstoEqual for values, toBe for one reference
toEqual on a classA class instance can equal a plain object with the same fieldstoStrictEqual when the type matters
expect(fn())The throw happens before toThrow can catch itexpect(() => fn()).toThrow()
clearAllMocksHistory is empty, and mockReturnValue is still installedresetAllMocks to drop the fake return. restoreAllMocks for spies
Floating resolvesThe test ends before the promise settlesReturn the expectation, or await it
Outer variable in jest.mockThe hoisted factory cannot see a normal bindingA name that starts with mock, or build the fake inside the factory

How to use this page: pick the matcher for the kind of value, await promises, and restore spies before the next test.