📋 Cheat Sheets

Jest Cheat Sheet — Write Better JavaScript Tests


Click any item to expand the explanation and examples.

🚀 Running Tests

jest CLI cli
# Run all tests
npx jest

Watch mode (re-run on changes)

npx jest —watch

Run specific file

npx jest users.test.js

Run tests matching a name

npx jest -t “should create user”

Coverage

npx jest —coverage

Verbose

npx jest —verbose

Run only changed files

npx jest —onlyChanged

Clear cache

npx jest —clearCache

✅ Matchers

Common matchers matcher
// Equality
expect(value).toBe(42);              // Strict equality (===)
expect(value).toEqual({a: 1});       // Deep equality (objects/arrays)
expect(value).toStrictEqual({a: 1}); // Deep + no extra properties

// Truthiness expect(value).toBeTruthy(); expect(value).toBeFalsy(); expect(value).toBeNull(); expect(value).toBeUndefined(); expect(value).toBeDefined();

// Numbers expect(value).toBeGreaterThan(3); expect(value).toBeGreaterThanOrEqual(3); expect(value).toBeLessThan(5); expect(value).toBeCloseTo(0.3, 5); // Floating point

// Strings expect(str).toMatch(/regex/); expect(str).toContain(“substring”);

// Arrays expect(arr).toContain(item); expect(arr).toHaveLength(3); expect(arr).toEqual(expect.arrayContaining([1, 2]));

// Objects expect(obj).toHaveProperty(“name”); expect(obj).toHaveProperty(“address.city”, “Brussels”); expect(obj).toMatchObject({name: “Alice”}); // Partial match

// Negation expect(value).not.toBe(42);

Exceptions matcher
// Test that function throws
expect(() => dangerousCall()).toThrow();
expect(() => dangerousCall()).toThrow("specific message");
expect(() => dangerousCall()).toThrow(TypeError);
expect(() => dangerousCall()).toThrow(/regex/);

📦 Structure

describe, test, beforeEach structure
describe("UserService", () => {
  let service;

beforeAll(() => { // Runs once before all tests in this describe });

beforeEach(() => { // Runs before each test service = new UserService(); });

afterEach(() => { // Runs after each test });

afterAll(() => { // Runs once after all tests });

test(“should create a user”, () => { const user = service.create(“Alice”); expect(user.name).toBe(“Alice”); });

test(“should throw on empty name”, () => { expect(() => service.create("")).toThrow(); });

// Skip or focus test.skip(“not ready yet”, () => {}); test.only(“run only this test”, () => {}); test.todo(“implement password validation”); });

🎭 Mocking

jest.fn() — mock functions mock
// Create a mock function
const mockFn = jest.fn();
mockFn("hello");

expect(mockFn).toHaveBeenCalled(); expect(mockFn).toHaveBeenCalledWith(“hello”); expect(mockFn).toHaveBeenCalledTimes(1);

// Mock return value const mockFn = jest.fn().mockReturnValue(42); const mockFn = jest.fn().mockReturnValueOnce(1).mockReturnValueOnce(2);

// Mock implementation const mockFn = jest.fn((x) => x * 2);

// Mock resolved/rejected value (async) const mockFn = jest.fn().mockResolvedValue({id: 1}); const mockFn = jest.fn().mockRejectedValue(new Error(“fail”));

jest.mock() — mock modules mock
// Mock entire module
jest.mock("./userService");
const { getUser } = require("./userService");
getUser.mockResolvedValue({name: "Alice"});

// Mock with implementation jest.mock(”./userService”, () => ({ getUser: jest.fn().mockResolvedValue({name: “Alice”}), createUser: jest.fn(), }));

// Mock node module jest.mock(“axios”); const axios = require(“axios”); axios.get.mockResolvedValue({data: {users: []}});

// Spy on existing method const spy = jest.spyOn(console, “log”).mockImplementation(); // … test … expect(spy).toHaveBeenCalledWith(“expected message”); spy.mockRestore();

Mock timers mock
jest.useFakeTimers();

test(“debounce”, () => { const callback = jest.fn(); debounce(callback, 1000)();

expect(callback).not.toHaveBeenCalled(); jest.advanceTimersByTime(1000); expect(callback).toHaveBeenCalledTimes(1); });

// Run all pending timers jest.runAllTimers();

// Restore real timers jest.useRealTimers();

⏳ Async Testing

async/await, promises, callbacks async
// async/await (recommended)
test("fetches user", async () => {
  const user = await fetchUser(1);
  expect(user.name).toBe("Alice");
});

// Resolves / rejects test(“resolves”, async () => { await expect(fetchUser(1)).resolves.toEqual({name: “Alice”}); });

test(“rejects”, async () => { await expect(fetchUser(-1)).rejects.toThrow(“not found”); });

// Callback style (use done) test(“callback”, (done) => { fetchUser(1, (err, user) => { expect(user.name).toBe(“Alice”); done(); }); });

📸 Snapshots

toMatchSnapshot snapshot
test("renders correctly", () => {
  const tree = renderer.create(<Button label="Click" />).toJSON();
  expect(tree).toMatchSnapshot();
});

// Inline snapshot test(“config”, () => { expect(getConfig()).toMatchInlineSnapshot( { "port": 3000, "debug": false, } ); });

// Update snapshots when intentional changes are made // npx jest —updateSnapshot // npx jest -u

⚡ each — table-driven tests

test.each pattern
test.each([
  [1, 2, 3],
  [0, 0, 0],
  [-1, 1, 0],
])("add(%i, %i) = %i", (a, b, expected) => {
  expect(add(a, b)).toBe(expected);
});

// With objects test.each([ {input: "", expected: false}, {input: “a@b.com”, expected: true}, ])(“validate($input) = $expected”, ({input, expected}) => { expect(isValidEmail(input)).toBe(expected); });