What is Jest?

Jest is a popular JavaScript test runner and assertion framework that bundles everything needed to test JavaScript and TypeScript code: test discovery, describe/test blocks, expect matchers, mocking, snapshot testing, coverage and a watch mode.

Core features

  • Zero-config start for many projects, with parallel test execution.
  • Matchers: toBe, toEqual (deep equality), toMatchObject, toContain, toThrow, resolves/rejects for promises, and many more.
  • Mocks: jest.fn() for spies, jest.mock("module") to replace whole modules, jest.spyOn(obj, "method").
  • Fake timers: jest.useFakeTimers() and jest.advanceTimersByTime(ms) to test debounce, timeouts and intervals instantly.
  • Snapshots: toMatchSnapshot() for serialisable output.
  • Coverage: --coverage uses V8 or Istanbul.
  • Environments: node by default, or jsdom to simulate a browser DOM.

Lifecycle hooks

beforeAll, beforeEach, afterEach, afterAll for setup and cleanup.

Jest vs Vitest

Vitest offers a Jest-compatible API, native ES modules and TypeScript, and very fast startup through Vite, so many new projects (especially Vite-based ones) choose it. Jest remains widespread, works well with Next.js through next/jest, and has a huge ecosystem. Knowing the shared API covers both.

Tips

  • Use toEqual for objects and arrays, toBe for primitives and identity.
  • Always await async assertions (await expect(p).rejects.toThrow()).
  • Reset mocks between tests (clearMocks / restoreMocks in config).

Code example

js
1// debounce.js
2export function debounce(fn, wait) {
3 let t;
4 return (...args) => {
5 clearTimeout(t);
6 t = setTimeout(() => fn(...args), wait);
7 };
8}
9
10// debounce.test.js (Jest)
11import { describe, test, expect, jest, beforeEach, afterEach } from "@jest/globals";
12import { debounce } from "./debounce.js";
13
14describe("debounce", () => {
15 beforeEach(() => jest.useFakeTimers());
16 afterEach(() => jest.useRealTimers());
17
18 test("calls the function once with the latest arguments", () => {
19 const spy = jest.fn();
20 const debounced = debounce(spy, 300);
21
22 debounced("a");
23 debounced("b");
24 debounced("c");
25 expect(spy).not.toHaveBeenCalled();
26
27 jest.advanceTimersByTime(300); // no real waiting
28 expect(spy).toHaveBeenCalledTimes(1);
29 expect(spy).toHaveBeenCalledWith("c");
30 });
31
32 test("async helpers", async () => {
33 const load = jest.fn().mockResolvedValue({ id: 1 });
34 await expect(load()).resolves.toEqual({ id: 1 });
35 await expect(Promise.reject(new Error("boom"))).rejects.toThrow("boom");
36 });
37});

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app