ReactEasy

What is Jest?

Jest is a JavaScript testing framework from Meta (now maintained under the OpenJS Foundation) that provides a test runner, assertions (expect), mocking, snapshot testing and coverage in one package. It has long been the default for React testing; version 30 is current, and many newer Vite-based projects use Vitest, which has a Jest-compatible API.

Features

  • describe, it/test, beforeEach, afterAll.
  • Matchers: toBe, toEqual, toHaveBeenCalledWith, toThrow, plus DOM matchers from @testing-library/jest-dom (toBeInTheDocument, toHaveTextContent).
  • Mocking: jest.fn(), jest.spyOn, jest.mock("module"), fake timers (jest.useFakeTimers()).
  • Snapshot testing (use sparingly; large snapshots are rarely reviewed).
  • Coverage reports, watch mode, parallel test files.
  • jsdom environment to test DOM code in Node.js.

Setup for React

  • Transform TypeScript and JSX with babel-jest, ts-jest or @swc/jest.
  • testEnvironment: "jsdom" and install jest-environment-jsdom.
  • Setup file importing @testing-library/jest-dom.
  • Frameworks provide presets, such as next/jest in Next.js.

Jest vs Vitest

  • Vitest: reuses the Vite config, native ESM and TypeScript, very fast watch mode, browser mode. Natural choice for Vite apps.
  • Jest: mature, huge ecosystem, default in many existing codebases and React Native. The APIs are nearly identical (vi.fn vs jest.fn), so knowledge transfers.

Code example

tsx
1// formatPrice.ts
2export function formatPrice(cents: number, currency = "USD") {
3 if (!Number.isInteger(cents)) throw new TypeError("cents must be an integer");
4 return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(cents / 100);
5}
6
7// formatPrice.test.ts (Jest)
8describe("formatPrice", () => {
9 it("formats cents as currency", () => {
10 expect(formatPrice(1999)).toBe("$19.99");
11 expect(formatPrice(500, "EUR")).toBe("€5.00");
12 });
13
14 it("rejects fractional cents", () => {
15 expect(() => formatPrice(10.5)).toThrow(TypeError);
16 });
17});
18
19// Mocking a module and timers
20// jest.mock("./api", () => ({ fetchUser: jest.fn().mockResolvedValue({ name: "Ada" }) }));
21// jest.useFakeTimers(); jest.advanceTimersByTime(1000);
22
23// jest.config.ts
24// export default { testEnvironment: "jsdom", setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"] };

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 React set.

Open in study app