Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 72 ยท Configuration, Tooling and Testing

Testing Next.js Apps

Test a Next.js app with the right tool for each layer: unit tests for logic, Vitest or Jest for components, Playwright for async server components and full flows.

Tests are how you change an app next month without being afraid of it. Next.js makes testing slightly unusual, because one codebase mixes code that runs in a browser (Client Components), code that runs on a server (Server Components, Server Actions, Route Handlers) and code that runs at build time. No single test tool covers all of that well, so the practical question is not "which framework?" but "which kind of test for which kind of code?".

This lesson gives you a map: what to test as plain functions, what to test with a component test runner, what to leave to a real browser, and how to write your code so most of it falls in the cheap category. Next.js, Vitest, Jest and Playwright cannot run on this site, so their configuration is read-only. The runnable examples are real tests, written with Node's built-in node:test runner, for Route Handler and Server Action logic that has been pulled out into plain functions. That is the most valuable technique in the lesson, and it needs no framework at all.

Pick the cheapest test that works

Plain functions Fast. Handlers, actions, validators, data helpers.
Component tests Vitest or Jest with a fake DOM for Client Components.
End to end Playwright drives a real browser against a real build.

Many cheap tests, a few expensive ones.

1 / 2

Make logic easy to test

The cheapest tests are for functions that take input and return output. Route Handlers and Server Actions are already functions, so they can be tested without starting Next.js, if you keep two habits:

  1. Standard objects in, standard objects out. A Route Handler receives a Web Request and returns a Web Response; both exist in Node, so a test can build a new Request(...) and read await response.json(). A Server Action used with a form receives a FormData, which also exists in Node.
  2. Inject what talks to the outside world. If the handler imports the database directly, a test needs a real database. If the handler is created from a store you pass in, a test passes a fake. The framework-only parts (revalidatePath, cookies(), redirect) can be passed in the same way, as in the examples below.

The real files stay tiny. For example app/api/notes/route.ts can contain export const { GET, POST } = createNotesRoute(realStore), and all the behavior lives in a normal module you can test.

Testing a Route Handler

The first example is a notes API. createNotesRoute is the code under test: it contains the logic you would normally write inside route.ts. The tests below it call GET and POST with real Request objects. The runner at the bottom is boilerplate that runs this same file in a child process in test mode and prints one line per test; with node --test on your own machine you would write only the tests. Route Handlers explains the Request/Response contract being tested here.

Node.js Testing a Route Handler as a plain function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Five tests run in a few milliseconds, with no server, no port and no database. Notice how each one covers a decision in the handler: success, filtering, creation, a validation failure and malformed input. In a real project the file would be named notes.test.ts and you would run it with Vitest or Jest; only the import lines and the test/expect spelling change.

Testing a Server Action

A Server Action used with useActionState has the signature (previousState, formData) => newState. It is also a plain async function. The framework calls that need a server (revalidatePath) can be injected and replaced with a spy, which records calls so the test can check that the action refreshed the right page and, just as important, did not refresh it after a failure.

Node.js Testing a Server Action with a spy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The important assertions are the negative ones: after a validation error nothing was saved and nothing was revalidated. Tests like these are where bugs in forms actually hide. Validating Input shows how to replace the hand-written checks with a schema while keeping the same tests.

Server Actions are public HTTP endpoints in disguise, so a thorough suite also tests that an unauthenticated caller is refused. Inject the "current user" the same way as the database.

Component tests with Vitest or Jest

Client Components (the ones marked "use client") are ordinary React components, and you can test them in a fake browser (jsdom) with React Testing Library. Next.js documents setups for both Vitest and Jest. A read-only Vitest configuration:

TypeScript
// vitest.config.mts (read-only)
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tsconfigPaths(), react()],
  test: { environment: "jsdom" },
});
TSX
// components/counter.test.tsx (read-only)
import { expect, test } from "vitest";
import userEvent from "@testing-library/user-event";
import { render, screen } from "@testing-library/react";
import Counter from "@/components/counter";

test("counts clicks", async () => {
  render(<Counter />);
  await userEvent.click(screen.getByRole("button", { name: /add one/i }));
  expect(screen.getByText("Count: 1")).toBeVisible();
});

Query by role and visible text, the way a user finds things, not by class names. Jest works the same way once you wrap its config with next/jest, which teaches it how to compile TypeScript, CSS imports and the @/ alias. Components that call useRouter, usePathname or useSearchParams need those hooks replaced, usually with vi.mock("next/navigation", ...) returning a small fake. Keep such mocks in one shared setup file so every test sees the same fake.

Setting up Jest, Vitest and Cypress step by step

The snippets above assume the tools are already configured. This section walks through the setup of each one. All files are read-only, since they configure tools that cannot run on this site. Pick one component test runner (Jest or Vitest); Cypress is an alternative to Playwright for browser tests. Check each tool's current Next.js guide for exact package versions.

Jest

Next.js ships next/jest, a helper that gives Jest the same compiler as your app, so TypeScript, JSX, CSS imports and image imports work without extra Babel configuration. It also loads your .env files and ignores node_modules and .next.

Terminal
npm install -D jest jest-environment-jsdom ts-node @types/jest @testing-library/react @testing-library/dom @testing-library/jest-dom
TypeScript
// jest.config.ts (read-only)
import type { Config } from "jest";
import nextJest from "next/jest.js";

const createJestConfig = nextJest({ dir: "./" }); // where next.config and .env live

const config: Config = {
  coverageProvider: "v8",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
  moduleNameMapper: { "^@/(.*)$": "<rootDir>/$1" }, // the "@/" import alias
};

export default createJestConfig(config);
TypeScript
// jest.setup.ts (read-only)
import "@testing-library/jest-dom";

Add "test": "jest" to the scripts in package.json and run npm test. testEnvironment: "jsdom" gives tests a fake document and window. The setup file runs before every test file, so it is the place for extra matchers such as toBeVisible() and for shared mocks. moduleNameMapper teaches Jest your @/ alias, which must match paths in tsconfig.json. Put /** @jest-environment node */ at the top of a test file that tests server code, so it runs without jsdom.

Vitest

Vitest uses Vite as its engine, so it starts fast and shares Vite's plugin system. It has a Jest-compatible API (describe, it, expect, vi.fn()), so most Jest knowledge carries over.

Terminal
npm install -D vitest @vitejs/plugin-react jsdom vite-tsconfig-paths @testing-library/react @testing-library/dom @testing-library/jest-dom
TypeScript
// vitest.config.mts (read-only)
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tsconfigPaths(), react()],
  test: {
    environment: "jsdom",
    setupFiles: ["./vitest.setup.ts"],
    globals: false, // import { test, expect } explicitly
  },
});
TypeScript
// vitest.setup.ts (read-only)
import "@testing-library/jest-dom/vitest";
import { vi } from "vitest";

// One shared fake for the router hooks, used by every test.
vi.mock("next/navigation", () => ({
  useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),
  usePathname: () => "/",
  useSearchParams: () => new URLSearchParams(),
}));

Add "test": "vitest"; it runs in watch mode locally and vitest run runs once for CI. vite-tsconfig-paths reads the aliases from tsconfig.json, so no moduleNameMapper is needed. The .mts extension makes Node treat the config as an ES module.

The stand-in below shows what that shared vi.mock("next/navigation") accomplishes. The component takes its router from one module. In a test, that module is swapped for a fake that records calls, so the test can check navigation without a real router.

Node.js What a shared router mock does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Cypress

Cypress runs in a real browser and shows each command and the page state in a time-travel interface, which many teams find friendly while writing tests. It offers two kinds of tests: end-to-end (visit the running app) and component (mount one component in the browser, with no server).

Terminal
npm install -D cypress
TypeScript
// cypress.config.ts (read-only)
import { defineConfig } from "cypress";

export default defineConfig({
  e2e: {
    baseUrl: "http://localhost:3000",
    setupNodeEvents() {
      // register plugins or tasks here
    },
  },
  component: {
    devServer: { framework: "next", bundler: "webpack" },
  },
});

Add the scripts "cypress:open": "cypress open" and "cypress:run": "cypress run". An end-to-end test uses cy.visit with the base URL and retries assertions until they pass:

TypeScript
// cypress/e2e/navigation.cy.ts (read-only)
describe("navigation", () => {
  it("opens the about page from the home page", () => {
    cy.visit("/");
    cy.contains("a", "About").click();
    cy.url().should("include", "/about");
    cy.get("h1").should("contain", "About");
  });
});

A component test mounts a Client Component directly:

TSX
// cypress/component/counter.cy.tsx (read-only)
import Counter from "@/components/counter";

describe("<Counter />", () => {
  it("counts clicks", () => {
    cy.mount(<Counter />);
    cy.contains("button", "Add one").click();
    cy.contains("Count: 1").should("be.visible");
  });
});

Like Vitest and Jest, Cypress component tests cannot mount an async Server Component, so the same advice applies. For end-to-end runs, build the app first and start it, then run Cypress against it. In CI the helper package start-server-and-test does this in one command (for example start-server-and-test start http://localhost:3000 cypress:run). Cypress and Playwright cover the same ground: Playwright has built-in multi-browser and parallel runs and a larger API for network control, Cypress has the interactive runner and a simpler learning curve. Choose one, not both.

Which one to choose

  • Vitest for new projects: fastest feedback and simple config.
  • Jest when the team or an existing code base already uses it; next/jest makes it painless.
  • Playwright or Cypress for end-to-end journeys, never for unit-sized logic.
  • All of them leave async Server Components to end-to-end tests.

The async Server Component limit

This is the most common surprise. A page such as

TSX
// app/products/page.tsx (read-only)
export default async function ProductsPage() {
  const products = await getProducts();
  return <ProductList products={products} />;
}

is an async Server Component. Vitest, Jest and React Testing Library render components with the client renderer, which does not know how to await a component, so this cannot be rendered in a unit test. Do not fight it. Split the work so each part has a test that fits:

  • getProducts() is a plain function: test it with a fake database, as in the examples above.
  • ProductList takes props and has no data fetching, so it is a normal component: test it with Testing Library.
  • The glue in ProductsPage is three lines. Cover it with an end-to-end test.

This is the same advice as pushing the client boundary down: small pieces with clear inputs.

End-to-end tests with Playwright

An end-to-end (e2e) test drives a real browser against a running app. It is the only layer that exercises routing, layouts, streaming, caching, cookies and middleware exactly as a visitor meets them. The usual setup builds the app and lets Playwright start it:

TypeScript
// playwright.config.ts (read-only)
import { defineConfig } from "@playwright/test";

export default defineConfig({
  testDir: "./e2e",
  use: { baseURL: "http://localhost:3000" },
  webServer: {
    command: "npm run build && npm run start",
    url: "http://localhost:3000",
    reuseExistingServer: !process.env.CI,
  },
});
TypeScript
// e2e/todos.spec.ts (read-only)
import { expect, test } from "@playwright/test";

test("a visitor can add a todo", async ({ page }) => {
  await page.goto("/todos");
  await page.getByLabel("Title").fill("Buy milk");
  await page.getByRole("button", { name: "Add" }).click();
  await expect(page.getByText("Buy milk")).toBeVisible();
});

Run e2e tests against a production build (build then start), not next dev: caching, static generation and error pages behave differently in development, and the dev server compiles pages on first visit, which makes tests slow and flaky. Give the tests a throwaway database that you reset before each run, and stub third-party services with page.route() so that a payment provider's outage does not fail your build. Auto-waiting assertions such as expect(...).toBeVisible() retry for you; avoid fixed sleeps.

Because e2e tests are slow, spend them on journeys: sign up, add to cart, check out. Leave edge cases (every validation message, every error status) to the cheap tests above.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a Route Handler be unit tested without starting Next.js?

    A handler uses Web standard objects. A test can construct a Request, call the function and read the Response with no server involved.
  2. 2. What is the usual way to test an async Server Component page?

    Component test renderers cannot await a Server Component. Splitting out the logic and the pure UI lets cheap tests cover most of the code, with e2e covering the glue.
  3. 3. Why inject revalidatePath into an action instead of importing it inside?

    revalidatePath needs the Next.js server runtime. Passing it in lets a test replace it with a recording function.
  4. 4. Which setup is best for Playwright e2e tests?

    A production build behaves like the real site, a disposable database keeps runs repeatable, and stubs remove outside failures.

Summary

  • Match the tool to the code: plain tests for logic, Vitest or Jest with jsdom for Client Components, Playwright for whole journeys.
  • Route Handlers and Server Actions are plain functions over Request/Response and FormData; inject databases and framework calls so tests can fake them.
  • Check the failure paths too: nothing saved, nothing revalidated, a clear error returned.
  • Async Server Components cannot be unit rendered; split data access and presentation, and let e2e tests cover the page.
  • Run e2e tests against next build plus next start with a resettable database and stubbed external services.

Next: Debugging and Error Handling