liminfo

Jest Reference

Free reference guide: Jest Reference

52 results

About Jest Reference

The Jest Reference is a complete, searchable cheat sheet for the Jest JavaScript testing framework. It is organized into eight categories that follow the natural workflow of writing tests: Basics (test, describe, it, beforeEach, afterEach, beforeAll, afterAll, test.only, test.skip), Matchers (toBe, toEqual, toStrictEqual, toBeTruthy, toBeFalsy, toBeNull, toBeUndefined, toContain, toThrow, toMatch, toBeGreaterThan, toHaveLength, toHaveProperty), Mocking (jest.fn, mockReturnValue, mockResolvedValue, jest.mock, jest.spyOn, toHaveBeenCalled, toHaveBeenCalledTimes, jest.useFakeTimers), Async (async/await, resolves, rejects, done callback, jest.setTimeout), Snapshot (toMatchSnapshot, toMatchInlineSnapshot, --updateSnapshot, toThrowErrorMatchingSnapshot), Config (jest.config.js, transform, moduleNameMapper, setupFilesAfterFramework), Coverage (--coverage, coverageDirectory, collectCoverageFrom, coverageThreshold), and CLI (--watch, --verbose, pattern matching, --bail, --runInBand).

This reference serves JavaScript and TypeScript developers writing unit tests, integration tests, and component tests with Jest. It covers common patterns used across React, Node.js, and general TypeScript projects. The mocking section is especially thorough, covering module mocking, function spying, Promise mocking with mockResolvedValue, and timer mocking with useFakeTimers — the four most common mocking scenarios in real-world test suites.

The coverage and CLI sections are targeted at engineers setting up CI pipelines and enforcing quality gates. The coverageThreshold configuration lets teams require minimum branch, function, and line coverage globally, preventing regressions from being merged. The CLI section covers the most useful flags for running tests locally during development (--watch), in CI (--runInBand, --bail), and for debugging (--verbose).

Key Features

  • Complete lifecycle hooks: beforeEach, afterEach, beforeAll, afterAll with async examples
  • toBe vs toEqual vs toStrictEqual: strict equality, deep equality, and undefined property comparison
  • jest.fn() mock functions with mockReturnValue, mockResolvedValue, and call assertion matchers
  • jest.spyOn() for spying on and mocking specific methods while preserving the original implementation
  • jest.mock(module) for auto-mocking entire modules in tests
  • Async test patterns: async/await, .resolves/.rejects chaining, done callback, and setTimeout
  • Snapshot testing with toMatchSnapshot(), toMatchInlineSnapshot(), and update flags
  • Coverage configuration: collectCoverageFrom glob patterns and coverageThreshold enforcement

Frequently Asked Questions

What is the difference between toBe and toEqual in Jest?

toBe uses strict equality (===) and is best for primitives like numbers, strings, and booleans. toEqual recursively checks that two objects have the same structure and values, making it the right choice for comparing objects and arrays. For objects, toBe checks reference equality (same object in memory), not structural equality.

How do I mock a module in Jest?

Call jest.mock("./your-module") at the top of your test file. Jest replaces the real module with an auto-mocked version where all exported functions become jest.fn(). You can then control return values with mockReturnValue or mockResolvedValue, and assert calls with toHaveBeenCalledWith.

What is the difference between jest.fn() and jest.spyOn()?

jest.fn() creates a standalone mock function not attached to any real implementation. jest.spyOn(object, method) replaces a method on an existing object with a spy, allowing you to intercept calls while optionally keeping the original implementation. Use spyOn when you want to monitor calls to a real method in a real module.

How do I test asynchronous code with Jest?

Jest supports three patterns: async/await (mark the test callback async and await the promise), .resolves/.rejects matchers (return the expect(...).resolves.toBe(...) from the test), and the done callback (call done() when the async operation is complete). The async/await pattern is generally the clearest.

How do I test code that uses setTimeout or setInterval?

Call jest.useFakeTimers() at the start of the test to replace browser timer functions with fake implementations. Then use jest.advanceTimersByTime(ms) to fast-forward time without actually waiting. This lets you test time-dependent code synchronously and much faster.

What does toMatchSnapshot do and when should I use it?

toMatchSnapshot() serializes the value and compares it against a stored snapshot file. If no snapshot exists it creates one; on subsequent runs it fails if the output has changed. It is most useful for UI component testing to catch unintended rendering changes. Run jest --updateSnapshot to update snapshots when you intentionally change the output.

How do I enforce minimum code coverage in Jest?

Set coverageThreshold in jest.config.js with keys branches, functions, lines, and statements. If coverage falls below the thresholds, the test run exits with a non-zero code, failing your CI pipeline. Use collectCoverageFrom to specify which files to include in coverage analysis.

What does jest --runInBand do?

--runInBand forces Jest to run all tests serially in the same process instead of using a worker pool. This is useful for debugging (to see console output in order), for tests that share state through a real database, or in CI environments with limited resources.