Next.jsMedium

What is the recommended testing setup for Next.js (Jest + Testing Library)?

Install Jest, jest-environment-jsdom, React Testing Library and @testing-library/jest-dom, then create jest.config.ts using nextJest({ dir: "./" }) from next/jest. That preset configures SWC transforms, CSS and image mocks, .env loading, path aliases and next.config for you. Vitest is an equally supported, faster alternative.

Install

npm i -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-event ts-node @types/jest

What next/jest handles

  • Transforms TS/JSX with Next.js's SWC compiler (no Babel config).
  • Mocks CSS, CSS Modules, images and fonts.
  • Loads .env.test and next.config.
  • Ignores node_modules and .next from transforms.
  • Respects paths from tsconfig when configured via moduleNameMapper or automatically in recent versions.

Writing tests

  • Query by role and label (getByRole("button", { name: /save/i })), not by class names.
  • Use user-event for realistic interactions.
  • Mock next/navigation (useRouter, usePathname, useSearchParams).
  • Server Functions imported by client components can be mocked with jest.mock("./actions").

Limits

Jest and Testing Library render synchronous components. Async Server Components are not supported; cover them with E2E tests, or test the data function separately and the presentational component with props.

Vitest variant

vitest, @vitejs/plugin-react, jsdom, vite-tsconfig-paths, with the same Testing Library APIs. Next.js publishes an official guide and example for both.

Code example

tsx
1// jest.config.ts
2import type { Config } from "jest";
3import nextJest from "next/jest.js";
4
5const createJestConfig = nextJest({ dir: "./" }); // loads next.config + .env files
6
7const config: Config = {
8 testEnvironment: "jsdom",
9 setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"], // import "@testing-library/jest-dom";
10 moduleNameMapper: { "^@/(.*)$": "<rootDir>/src/$1" },
11};
12
13export default createJestConfig(config);
14
15// src/components/counter.test.tsx
16// import { render, screen } from "@testing-library/react";
17// import userEvent from "@testing-library/user-event";
18// import { Counter } from "./counter";
19// test("increments", async () => {
20// render(<Counter start={1} />);
21// await userEvent.click(screen.getByRole("button", { name: "1" }));
22// expect(screen.getByRole("button", { name: "2" })).toBeInTheDocument();
23// });

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 Next.js set.

Open in study app