Jest Tutorial
Learn Jest step by step: 30 lessons in 11 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Jest? Learn what Jest does, how a test runner, assertions and mocks fit together, how Jest compares with Vitest and node:test, and what happens when a test file runs.
- Your First Jest Test Write your first Jest test: create a function, add a .test.js file, use test() and expect().toBe(), run npm test and learn to read a passing and failing report.
- describe, it and Test Organization Group Jest tests with describe, choose between it and test, use skip, only and todo, name tests so failures read clearly, and structure each test as arrange-act-assert.
- The Jest CLI and Watch Mode Learn the Jest command line: run one file, filter tests with -t, use watch mode, collect coverage, run in band, stop early with --bail and read exit codes in CI.
Matchers
- Common Matchers Learn the everyday Jest matchers: toBe versus toEqual versus toStrictEqual, truthiness matchers like toBeNull and toBeDefined, and how not flips any check.
- Numbers and Strings Use Jest's number and string matchers: toBeGreaterThan, toBeCloseTo for floating point, toMatch with regex, toContain and toHaveLength, with runnable stand-ins.
- Arrays and Objects Test arrays and objects in Jest with toContainEqual, toHaveProperty, toMatchObject, objectContaining, arrayContaining and expect.any, with a runnable stand-in.
- Errors and Custom Matchers Test thrown errors with Jest toThrow, wrap calls correctly, and write your own matchers with expect.extend and clear failure messages. Runnable stand-in.
Asynchronous Code
- Testing Promises and Async/Await Test promises and async functions in Jest: return or await them, use resolves and rejects, avoid the forgotten-await trap, and count assertions with expect.assertions.
- Callbacks and the done Callback Test callback-based code in Jest with the done argument, handle timeouts and errors, turn callbacks into promises with promisify, and learn why done is a legacy tool.
Hooks and Isolation
- Setup and Teardown Hooks Learn Jest setup and teardown: beforeEach, afterEach, beforeAll and afterAll, the order hooks run in across nested describe blocks, async hooks and common mistakes.
- Test Isolation and Shared State Why Jest tests pass alone but fail together: leaked state, module registries, order-dependent tests, test data factories and the usual causes of flaky tests.
Mocking
- Mock Functions with jest.fn Learn Jest mock functions: jest.fn, mock.calls and mock.results, mockReturnValue, mockImplementation, toHaveBeenCalledWith, plus a runnable stand-in built on node:test.
- Spying with jest.spyOn Use jest.spyOn to watch or replace methods on real objects: clear vs reset vs restore, restoreMocks config, spying on console and Math.random, with runnable stand-ins.
- Mocking Modules Replace whole modules in Jest with jest.mock: automock vs factory, hoisting, partial mocks with requireActual, ESM caveats, and dependency injection as a simpler alternative.
- Mocking Timers, Dates and HTTP Test time and network code in Jest: useFakeTimers, advanceTimersByTime, setSystemTime, async timer helpers and mocking fetch, with runnable node:test stand-ins.
Snapshots and Tables
- Snapshot Testing Learn Jest snapshot testing: toMatchSnapshot, toMatchInlineSnapshot, updating with -u, property matchers, and when snapshots help or hurt, with a runnable snapshot-store stand-in.
- Table-Driven Tests with test.each Run one Jest test over many inputs with test.each and describe.each: array tables, tagged template tables, printf title formatting, edge-case tables and a runnable stand-in.
Jest in Real Projects
- Configuring Jest Configure Jest with jest.config.js: testEnvironment, testMatch, setup files, moduleNameMapper, transform and projects, plus a runnable stand-in config loader.
- Coverage and Test Quality Measure code coverage with Jest: read the report, set coverageThreshold, understand line vs branch coverage and why coverage is not quality, with a coverage counter stand-in.
Testing Real Applications
- Testing UI with jsdom and Testing Library Test user interfaces in Jest with jsdom and Testing Library: query by role and accessible name, simulate user events, avoid brittle selectors, with browser stand-ins.
- Testing APIs and Databases Test HTTP APIs and database code with Jest: the Supertest idea, test data, in-memory databases, isolation between tests, with runnable node:sqlite and loopback server stand-ins.
Tooling and CI
Projects
- Project: Test a Shopping Cart Build and test a shopping cart module test-first with Jest: red-green-refactor, edge cases, a mocked price API and clear failure messages, with runnable stand-ins.
- Project: Test an API Client Build and test a small fetch-based API client: success paths, HTTP errors, network failures, retries with backoff and fake timers, with runnable stand-ins.
- Project: Test an Event System Test a small event emitter with Jest: spies on listeners, once and off, call order, errors inside listeners and async ordering, with runnable stand-ins.
- Project: Test a Form Validator Test a sign-up form validator with Jest: table-driven rules with test.each, a custom matcher for field errors and a snapshot of error messages, with stand-ins.
Practice and Review
- Jest Exercises with Solutions Ten Jest exercises with full solutions covering matchers, errors, async code, mocks, fake timers and table tests, plus runnable stand-ins to check your answers.
- Jest Interview Questions Prepare for Jest interviews: toBe vs toEqual, mocks vs spies, clear vs reset vs restore, fake timers, snapshots, async pitfalls and test strategy, with runnable stand-ins.
- 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.