Jest Cheat Sheet

Quick reference for Jest testing framework. Matchers, mocks, spies, async testing, setup/teardown, and common patterns — all in one page.

Test Structure Common Matchers Negation & Errors Mock Functions Module Mocks Async Testing Setup & Teardown CLI Commands

Test Structure

describe("group", () => { ... }) Group related tests
test("does something", () => { ... }) Define a test (alias: it)
test.only("focus", () => { ... }) Run only this test
test.skip("skip", () => { ... }) Skip this test
test.todo("implement later") Placeholder for future test
test.each([[1,2,3], [2,3,5]])("add(%i,%i)=%i", (a,b,expected) => { ... }) Parameterized tests

Common Matchers

expect(x).toBe(y) Strict equality (===)
expect(x).toEqual(y) Deep equality (objects/arrays)
expect(x).toBeTruthy() Truthy value (not false, 0, "", null, undefined)
expect(x).toBeFalsy() Falsy value
expect(x).toBeNull() Strict null check
expect(x).toBeUndefined() Strict undefined check
expect(x).toBeDefined() Not undefined
expect(x).toBeGreaterThan(3) Number comparison (>, >=, <, <=)
expect(x).toBeCloseTo(0.3, 5) Float comparison (precision)
expect(str).toMatch(/regex/) Regex or substring match
expect(arr).toContain(item) Array contains item
expect(obj).toHaveProperty("key", value) Object has property
expect(arr).toHaveLength(3) Array/string length

Negation & Errors

expect(x).not.toBe(y) Negate any matcher
expect(() => fn()).toThrow() Function throws any error
expect(() => fn()).toThrow("message") Throws with specific message
expect(() => fn()).toThrow(TypeError) Throws specific error type
expect(x).toMatchSnapshot() Match stored snapshot
expect(x).toMatchInlineSnapshot(`value`) Inline snapshot

Mock Functions

const fn = jest.fn() Create mock function
const fn = jest.fn(() => 42) Mock with return value
fn.mockReturnValue(42) Set return value
fn.mockReturnValueOnce(42) Return value once, then default
fn.mockResolvedValue(data) Mock async function (returns Promise)
fn.mockImplementation((x) => x * 2) Custom implementation
expect(fn).toHaveBeenCalled() Was function called?
expect(fn).toHaveBeenCalledTimes(3) Called N times?
expect(fn).toHaveBeenCalledWith(arg1, arg2) Called with specific args?
fn.mockClear() Clear call history (not implementation)
fn.mockReset() Clear everything (history + implementation)

Module Mocks

jest.mock("./module") Auto-mock entire module
jest.mock("./module", () => ({ fn: jest.fn() })) Manual mock factory
jest.spyOn(obj, "method") Spy on existing method
jest.spyOn(obj, "method").mockReturnValue(42) Spy + override return
jest.requireActual("./module") Get original (unmocked) module
jest.useFakeTimers() Mock setTimeout/setInterval
jest.advanceTimersByTime(1000) Fast-forward fake timers

Async Testing

test("async", async () => { await expect(fn()).resolves.toBe(42); }) Async/await with resolves
test("async", async () => { const result = await fn(); expect(result).toBe(42); }) Async/await direct
test("rejects", async () => { await expect(fn()).rejects.toThrow("err"); }) Test promise rejection
test("callback", (done) => { fn((data) => { expect(data).toBe(42); done(); }); }) Callback-style test

Setup & Teardown

beforeEach(() => { ... }) Run before each test in block
afterEach(() => { ... }) Run after each test in block
beforeAll(() => { ... }) Run once before all tests in block
afterAll(() => { ... }) Run once after all tests in block
jest.setTimeout(10000) Set test timeout (ms)

CLI Commands

npx jest Run all tests
npx jest --watch Watch mode (re-run on changes)
npx jest --coverage Generate coverage report
npx jest path/to/test.js Run specific test file
npx jest -t "test name" Run tests matching name pattern
npx jest --verbose Show individual test results
npx jest --updateSnapshot Update stored snapshots
Step-by-Step Guide

How to Format JSON Online

Read Guide →

More Cheat Sheets