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/rejectsfor promises, and many more. - Mocks:
jest.fn()for spies,jest.mock("module")to replace whole modules,jest.spyOn(obj, "method"). - Fake timers:
jest.useFakeTimers()andjest.advanceTimersByTime(ms)to test debounce, timeouts and intervals instantly. - Snapshots:
toMatchSnapshot()for serialisable output. - Coverage:
--coverageuses V8 or Istanbul. - Environments:
nodeby default, orjsdomto 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
toEqualfor objects and arrays,toBefor primitives and identity. - Always
awaitasync assertions (await expect(p).rejects.toThrow()). - Reset mocks between tests (
clearMocks/restoreMocksin config).
Code example
1// debounce.js2export function debounce(fn, wait) {3 let t;4 return (...args) => {5 clearTimeout(t);6 t = setTimeout(() => fn(...args), wait);7 };8}910// debounce.test.js (Jest)11import { describe, test, expect, jest, beforeEach, afterEach } from "@jest/globals";12import { debounce } from "./debounce.js";1314describe("debounce", () => {15 beforeEach(() => jest.useFakeTimers());16 afterEach(() => jest.useRealTimers());1718 test("calls the function once with the latest arguments", () => {19 const spy = jest.fn();20 const debounced = debounce(spy, 300);2122 debounced("a");23 debounced("b");24 debounced("c");25 expect(spy).not.toHaveBeenCalled();2627 jest.advanceTimersByTime(300); // no real waiting28 expect(spy).toHaveBeenCalledTimes(1);29 expect(spy).toHaveBeenCalledWith("c");30 });3132 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.