Next.jsMedium
How do you test Next.js applications?
Use layers: unit tests for utilities, schemas and permission logic (Vitest or Jest), component tests for Client and synchronous Server Components (React Testing Library), and end-to-end tests with Playwright or Cypress for full user flows, including async Server Components, Server Functions, routing and caching. The Next.js docs recommend E2E for async Server Components because unit test runners do not fully support them.
Layers
- Unit: pure functions such as formatters, Zod schemas,
can()permission checks, reducers. Fast and many. - Component: render Client Components, simulate events, assert on accessible output. Mock
next/navigationhooks. - Integration: Route Handlers called directly with a
Request, Server Functions called as functions with a mocked database or a test database. - E2E:
next build && next start, then a browser test runner covering sign-up, checkout, navigation and prefetching.
Tooling choices
- Vitest with
@vitejs/plugin-react,jsdomandvite-tsconfig-paths: fast, ESM-native, popular for new projects. - Jest with
next/jest, which loadsnext.config, env files and SWC transforms. - Playwright: cross-browser E2E, tracing,
webServerto start the app.@next/playwrightadds aninstant()helper (16.3) to assert what is visible during a navigation before dynamic data streams in. - Cypress: E2E and component testing.
- MSW to mock network requests in tests.
Tips
- Run E2E against a production build; dev behaves differently (no prefetching, no caching).
- Test Proxy logic with
unstable_doesMiddlewareMatch,isRewriteandgetRewrittenUrlfromnext/experimental/testing/server. - Keep business logic out of components so most tests are cheap unit tests.
Code example
tsx
1// vitest.config.mts2// import { defineConfig } from "vitest/config";3// import react from "@vitejs/plugin-react";4// import tsconfigPaths from "vite-tsconfig-paths";5// export default defineConfig({ plugins: [tsconfigPaths(), react()], test: { environment: "jsdom" } });67// lib/permissions.test.ts - unit8import { describe, it, expect } from "vitest";9import { can } from "./permissions";1011describe("can()", () => {12 it("lets editors update only their own posts", () => {13 const editor = { id: "u1", role: "editor" as const };14 expect(can(editor, "post:update", { authorId: "u1" })).toBe(true);15 expect(can(editor, "post:update", { authorId: "u2" })).toBe(false);16 });1718 it("only admins delete", () => {19 expect(can({ id: "a", role: "admin" }, "post:delete")).toBe(true);20 expect(can({ id: "e", role: "editor" }, "post:delete")).toBe(false);21 });22});2324// e2e/checkout.spec.ts - Playwright against `next build && next start`25// test("checkout", async ({ page }) => { await page.goto("/"); await page.getByRole("link", { name: "Shop" }).click(); ... });
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.