Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 30 ยท Practice and Review

Jest Cheat Sheet

A one-page Jest cheat sheet: structure, matchers, async patterns, mocks and spies, fake timers, hooks, CLI flags and config options, with runnable stand-ins.

This page puts the whole Jest toolbox on one screen so you can look things up fast. Every table links to the lesson that explains the topic. It is a memory aid, not a teaching text: if a row surprises you, follow the link.

Jest itself does not run on this site, so the Jest snippets are read-only. Two runnable stand-ins at the end show the idea behind matchers and mock call records with plain Node code. They are stand-ins, not Jest, and they say so.

The test loop

Arrange Build the input and fakes.
Act Call the code once.
Assert expect(...) with the right matcher.

Three steps per test keeps tests short and honest.

1 / 2

Structure

Need Code
A test test("name", () => {}) or it("name", ...)
Group tests describe("unit", () => { ... })
Skip / focus / placeholder test.skip, test.only, test.todo("later")
Table of cases test.each([[1, 2], [3, 4]])("add %i", (a, b) => {})
Table as a template literal test.each followed by a tagged template with a header row
Group table describe.each([...])("%s", ...)

See describe, it and Test Organization and Table-Driven Tests with test.each.

Matchers

Question Matcher
Same value or same object (identity) toBe(x)
Same by value (ignores undefined props) toEqual(x)
Same by value, strict on types and undefined toStrictEqual(x)
Truthiness toBeTruthy(), toBeFalsy(), toBeNull(), toBeUndefined(), toBeDefined()
Numbers toBeGreaterThan(n), toBeLessThanOrEqual(n), toBeCloseTo(n, digits)
Strings toMatch(/regex/), toContain("sub"), toHaveLength(n)
Arrays toContain(item), toContainEqual(obj), expect.arrayContaining([...])
Objects toHaveProperty("a.b", value?), toMatchObject({...}), expect.objectContaining({...})
Any type / any text expect.any(Number), expect.stringContaining("x")
Errors expect(() => fn()).toThrow(Error or "message" or /regex/)
Negation .not.toBe(x)
Custom expect.extend({ toBeEven(received) { return { pass, message } } })

See Common Matchers, Numbers and Strings, Arrays and Objects and Errors and Custom Matchers.

Async patterns

JavaScript
test("promise, resolved", async () => {
  await expect(load()).resolves.toEqual({ ok: true });
});

test("promise, rejected", async () => {
  await expect(load(0)).rejects.toThrow("invalid id");
});

test("plain await", async () => {
  const data = await load();
  expect(data.ok).toBe(true);
});

test("assertions actually ran", async () => {
  expect.assertions(1);
  await expect(load()).resolves.toBeDefined();
});

Always await or return the promise. Use done only for callback APIs you cannot wrap: Testing Promises and Async/Await, Callbacks and the done Callback.

Mocks and spies

Need Code
New mock function const fn = jest.fn()
Return value / implementation fn.mockReturnValue(1), fn.mockResolvedValue(x), fn.mockImplementation(...)
One-time behavior fn.mockReturnValueOnce(1), fn.mockRejectedValueOnce(err)
Assert calls toHaveBeenCalled(), toHaveBeenCalledTimes(n), toHaveBeenCalledWith(...), toHaveBeenLastCalledWith(...), toHaveBeenNthCalledWith(n, ...)
Inspect calls fn.mock.calls, fn.mock.results, fn.mock.lastCall
Spy on a method jest.spyOn(obj, "method")
Replace a module jest.mock("./module") or jest.mock("./module", () => ({ ... }))
Forget calls mockClear()
Also drop behavior mockReset()
Also reinstall original mockRestore()
All at once jest.clearAllMocks(), jest.resetAllMocks(), jest.restoreAllMocks()

See Mock Functions with jest.fn, Spying with jest.spyOn and Mocking Modules.

Fake timers and snapshots

Need Code
Turn fake timers on / off jest.useFakeTimers() / jest.useRealTimers()
Move the clock jest.advanceTimersByTime(ms)
Run everything pending jest.runAllTimers(), jest.runOnlyPendingTimers()
With promises await jest.advanceTimersByTimeAsync(ms)
Fix the date jest.setSystemTime(new Date("2030-01-01"))
Snapshot in a file / inline toMatchSnapshot() / toMatchInlineSnapshot()
Update snapshots jest --updateSnapshot or -u

See Mocking Timers, Dates and HTTP and Snapshot Testing.

Hooks

Hook Runs
beforeAll(fn) once before all tests in the block
beforeEach(fn) before every test
afterEach(fn) after every test (cleanup)
afterAll(fn) once after all tests in the block

before hooks run outer to inner, after hooks run inner to outer. See Setup and Teardown Hooks and Test Isolation and Shared State.

CLI flags

Command Effect
npx jest run all tests
npx jest path/to/file run matching files
npx jest -t "name" run tests whose name matches
--watch rerun on changes (needs Git)
--coverage print a coverage report
--runInBand (-i) run in the current process, one file at a time
--bail stop after the first failing test suite
--ci do not write new snapshots
--updateSnapshot (-u) rewrite snapshots
--verbose one line per test

Exit code 0 means all passed, nonzero means failure: The Jest CLI and Watch Mode.

Config options

JavaScript
// jest.config.js
module.exports = {
  testEnvironment: "node",          // or "jsdom" for browser-like tests
  setupFilesAfterEnv: ["./setup.js"],
  testMatch: ["**/*.test.js"],
  moduleNameMapper: { "^@/(.*)$": "<rootDir>/src/$1" },
  transform: {},                    // babel-jest is the default
  clearMocks: true,
  restoreMocks: true,
  collectCoverageFrom: ["src/**/*.js"],
  coverageThreshold: { global: { branches: 80, lines: 80 } },
};

Details in Configuring Jest and Coverage and Test Quality.

Stand-in 1: a matcher is a function that returns pass or fail

All the matchers above follow one idea. A matcher takes the received value and returns whether it passes. This stand-in is a tiny expect() with three matchers and .not. It is NOT Jest's implementation.

Node.js Stand-in: a tiny expect with .not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third check fails on purpose: two separate objects are never toBe equal, even with the same contents. That is the single most common matcher mistake.

Stand-in 2: what a mock remembers

Every row in the "Inspect calls" table is a view of a list that the mock keeps while it runs. This stand-in builds the minimum: calls, results and a few toHaveBeenCalled... style checks. Again, it is only an illustration.

Node.js Stand-in: calls, results and a last-call check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which cleanup call also reinstalls the original method of a spy?

    mockRestore resets the mock and puts the original method back.
  2. 2. Which hook runs once before every test in a describe block?

    beforeEach runs before each test, while beforeAll runs a single time before the first one.
  3. 3. Which flag stops snapshot files from being written in CI?

    With --ci, a missing snapshot makes the test fail instead of being created, so nothing is accepted by accident.
  4. 4. How do you check that a function throws a specific message?

    Pass Jest a function that makes the call, so Jest can catch the error. Calling fn() yourself would throw first.

Summary

  • Structure with describe and test; use test.each for tables of cases.
  • Pick the matcher for the question: identity (toBe), value (toEqual), strict value (toStrictEqual), tolerance (toBeCloseTo).
  • Await or return every promise assertion; expect.assertions guards against skipped ones.
  • Mocks record calls; clear forgets calls, reset drops behavior, restore reinstalls originals.
  • Fake timers make time controllable; hooks keep tests independent; flags and config decide how and where tests run.

That is the whole kit. Revisit any topic from the beginning with What Is Jest?.