Explain it simply
Explain it simply
When a house is finished, an inspector does not use just one method. They check that each brick is solid, try the doors and light switches in every room, and finally walk from the front door to the kitchen the way a guest would.
A Next.js app works the same way. TypeScript catches wrong data shapes before anything runs. Unit tests check small rules such as validation in milliseconds. Component tests click buttons and fill forms like a user, and end-to-end tests drive a real browser through a whole journey such as "write a new note and save it".
Problem → Why → Solution
The problem: a test that cannot render, and a bug that got skipped
The /notes page in Myanmar Notes is an async Server Component that awaits notes from the database. A developer writes a test that renders the page directly with Testing Library, the way they did in a plain React app. The test fails with a confusing error, or hangs because there is no database connection.
Short on time, they mark it test.skip. Two weeks later a bug where titles are not trimmed reaches production, because the only test that would have covered that rule was the one that got skipped.
import { render, screen } from "@testing-library/react";
import { expect, test } from "vitest";
import NotesPage from "./page"; // async Server Component that queries the DB
test.skip("lists notes", () => {
// An async component returns a Promise, which this render cannot handle
render(<NotesPage />);
expect(screen.getByText("Mohinga recipe")).toBeTruthy();
});Why does this approach fail?
According to the Next.js testing guide, tools such as Vitest do not currently support async Server Components. When one page mixes data fetching, rules and rendering, it is hard to test at all. The fix is to pull the rules out into plain functions you can unit test, and to check the whole page with an end-to-end test in a real browser.
Core concept: each layer catches a different kind of bug
Test layers do not replace each other, because each one catches a different kind of bug. The lower you go, the faster and cheaper a check is; the higher you go, the closer it gets to what a user sees, and the slower it runs. That is why most tests live in the lower layers and only a handful of important journeys get an end-to-end test.
| Layer | Catches | Typical tool in Next.js |
|---|---|---|
| Type check | Wrong props, forgotten undefined cases | tsc --noEmit (next build checks too) |
| Unit | Wrong validation, formatting, permission rules | Vitest or Jest |
| Component | Dead buttons, missing labels, stuck state | Testing Library + jsdom |
| End-to-end | Broken routing, server and database wiring | Playwright (or Cypress) |
In Next.js the key rule depends on the kind of component. Client Components and synchronous Server Components can be rendered in jsdom with Vitest and Testing Library. Async Server Components are not supported by unit-test tools yet, so the Next.js docs recommend covering them with end-to-end tests.
That does not mean "leave async pages untested". Pull the parts of a page that involve decisions (checking a title, turning a search param into a page number, deciding who may edit) into plain functions in a lib/ folder. The page and the Server Action then just call those functions, and the rules become testable in milliseconds without a database.
Debugging is part of the workflow too
When a test fails, the first job is to make the bug reproducible. Writing down the expected result, the actual result, the steps and the environment (browser, Node version, dev server or production build) makes it far easier to track down. Then write the test that catches it before you write the fix.
- Type check catches wrong shapes
- Unit tests pin down the rules
- Component tests click like a user
- E2E walks the real journey
Write each test in the lowest layer that can catch the bug. That layer is usually the fastest and the least flaky.
General pattern: a Vitest unit test
import { describe, expect, it } from "vitest";
import { functionUnderTest } from "./module";
describe("functionUnderTest", () => {
it("describes one behaviour in plain words", () => {
expect(functionUnderTest(someInput)).toEqual(expectedValue);
});
});describe groups related tests, and each it checks one behaviour. After expect(actual) you chain a matcher such as toEqual (compares objects by value) or toBe (exact identity).
Example: testing the title rule from a Server Action
The title rule that used to live inside the create-note Server Action has been pulled out into a plain function, validateTitle. The Server Action now just calls it, so the rule can be tested without a database.
In a real project the test file imports describe, it and expect from vitest. So that this lesson's code runs with npx tsx and no installs, those three functions are replaced by a few lines of stand-in. The test bodies are exactly what you would write for Vitest.
import { deepStrictEqual } from "node:assert/strict";
// lib/validate-title.ts: the rule, pulled out of the Server Action
export type TitleResult =
| { ok: true; title: string }
| { ok: false; error: string };
export function validateTitle(raw: string): TitleResult {
const title = raw.trim();
if (title.length === 0) return { ok: false, error: "Title is required" };
if (title.length < 3) return { ok: false, error: "Title is too short" };
if (title.length > 80) return { ok: false, error: "Title is too long" };
return { ok: true, title };
}
// In a project the test file starts with:
// import { describe, expect, it } from "vitest";
// This small stand-in lets the file run with plain tsx instead.
const describe = (name: string, fn: () => void) => { console.log(name); fn(); };
const it = (name: string, fn: () => void) => {
try { fn(); console.log(` ✓ ${name}`); }
catch (err) { console.log(` ✗ ${name}: ${(err as Error).message}`); }
};
const expect = (actual: unknown) => ({
toEqual: (expected: unknown) => deepStrictEqual(actual, expected),
});
describe("validateTitle", () => {
it("rejects a title that is too short", () => {
expect(validateTitle("Hi")).toEqual({ ok: false, error: "Title is too short" });
});
it("treats a title of only spaces as missing", () => {
expect(validateTitle(" ")).toEqual({ ok: false, error: "Title is required" });
});
it("trims and accepts a valid title", () => {
const result = validateTitle(" Next.js Notes ");
expect(result).toEqual({ ok: true, title: "Next.js Notes" });
});
it("rejects a title longer than 80 characters", () => {
const tooLong = "x".repeat(81);
expect(validateTitle(tooLong)).toEqual({ ok: false, error: "Title is too long" });
});
});Code breakdown
- A result type instead of a thrown error
| { ok: false; error: string };validateTitle returns an object with ok and error instead of throwing. A Server Action can send that object straight back as form state, and a test can check it cleanly with toEqual.
- Trim before measuring
const title = raw.trim();Trimming first stops a title of three spaces from counting as length 3. The "only spaces" test guards exactly this edge case.
- The stand-in for Vitest
const expect = (actual: unknown) => ({Like Vitest's expect(...).toEqual(...), it compares by value using deepStrictEqual. In a real project you delete these lines and import from vitest instead.
- One behaviour per test
it("trims and accepts a valid title", () => {The test name describes behaviour, not how the function works inside. When it fails, the name alone tells you what broke.
- Boundary values
const tooLong = "x".repeat(81);Most bugs hide at the edges. Checking that 81 characters is rejected catches someone accidentally swapping > for >= later.
validateTitle
✓ rejects a title that is too short
✓ treats a title of only spaces as missing
✓ trims and accepts a valid title
✓ rejects a title longer than 80 charactersAdding Vitest to a Next.js project
1. Install the packages
The Next.js docs list Vitest, the React plugin, jsdom, Testing Library and a plugin that understands your tsconfig path aliases (@/...) as dev dependencies.
2. Create vitest.config.mts
Put a config file in the project root and set the test environment to jsdom. If you only test pure functions, the default node environment is enough.
3. Add a script and run it
Add "test": "vitest" to package.json. pnpm test runs in watch mode; in CI use vitest run to run once and exit.
pnpm add -D vitest @vitejs/plugin-react jsdom @testing-library/react \
@testing-library/dom vite-tsconfig-pathsimport { 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" },
});Testing a Client Component with Testing Library
A component marked "use client", such as NoteForm, runs in the browser, so you can render it in jsdom and type and click like a user. If it receives its Server Action as a prop, the test can simply pass in a vi.fn() mock. Finding elements by label and role instead of CSS class tests what the user actually sees.
import { fireEvent, render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { NoteForm } from "./note-form";
test("shows the validation message for a short title", async () => {
const save = vi.fn();
render(<NoteForm onSave={save} />);
fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Hi" } });
fireEvent.click(screen.getByRole("button", { name: "Save note" }));
expect(await screen.findByRole("alert")).toHaveProperty(
"textContent", "Title is too short");
expect(save).not.toHaveBeenCalled();
});End-to-end tests with Playwright
An E2E test opens a real browser and visits the app by URL. That makes it the only layer that checks whether async Server Components, Server Actions, redirects and the database really work together. The Next.js docs recommend running E2E tests against a production build started with next build and next start rather than next dev, because that is closer to what users get.
import { expect, test } from "@playwright/test";
test("a signed-in user can create a note", async ({ page }) => {
await page.goto("/dashboard/notes/new");
await page.getByLabel("Title").fill("Shan noodles");
await page.getByRole("button", { name: "Save note" }).click();
await expect(page).toHaveURL(/\/dashboard\/notes\/[\w-]+$/);
await expect(page.getByRole("heading", { name: "Shan noodles" })).toBeVisible();
});Let Playwright start the server
Set the webServer option in playwright.config.ts with a command (for example pnpm build && pnpm start) and a url, and Playwright starts the app before the tests and stops it afterwards. For flows behind a login, use a test-only user and a separate test database.
Debugging: where do the logs go?
In Next.js some code runs on the server and some in the browser, so console.log output appears in two places. If you look for a Server Action's log in the browser console, you will never find it. In development, recent Next.js versions may also replay Server Component logs in the browser console with a Server label, but the terminal is the real source.
| Where the code runs | Where to read its logs |
|---|---|
| Server Component, Server Action, Route Handler | The terminal running next dev (hosting logs in production) |
| Client Component event handlers and effects | The Console tab in browser DevTools |
| Requests and response status codes | The Network tab in DevTools |
When console.log is not enough, debug server code with the Node inspector. Start the dev server with NODE_OPTIONS='--inspect' next dev, open chrome://inspect in Chrome and set breakpoints (VS Code's debugger can attach too). In production, an error shown to users carries only an ID called a digest instead of the full message. Search for that digest in the server logs to find the complete stack trace.
In real projects
In real projects
On most teams, CI runs the type check, lint and unit and component tests on every pull request within a few minutes, and a failure blocks the merge. E2E tests are slower, so teams pick around five critical journeys such as "sign in, create a note, delete a note" and run them against a production build or a preview deployment.
When a bug report arrives, good teams first write a failing test that reproduces it. They watch it fail, write the fix and watch it pass. That way, if a later refactor brings the old bug back (a regression), the test raises the alarm immediately. Over months, these small reproduction tests become the most valuable part of the suite.
Common mistakes
Common mistakes
- Trying to render an async Server Component directly in Vitest and mocking half of Next.js to make it work. Pulling rules into plain functions and covering the whole page with E2E is simpler and more trustworthy.
- Testing implementation details: finding elements by CSS class or asserting on a component's internal state variable. A refactor that keeps behaviour identical breaks the test, while real bugs slip through.
- Silencing a failing test with test.skip, or deleting it, without finding the cause. A skipped test protects nothing. If you truly must skip one, leave a comment with a ticket link.
- Running E2E tests only against next dev. The dev server compiles routes on demand, which makes tests slow and prone to timeouts, and it hides caching problems that only appear in a production build.
Best practices
Best practices
- Keep decisions from Server Actions and pages in plain functions under lib/
- Check one behaviour per test and name it with a full sentence
- Reserve E2E for critical journeys and run it against a production build
- For every bug, write a failing test before writing the fix
Mini challenge
Try it yourself: test the page-number parser
Write parsePage, which reads the page number from a URL such as /notes?page=3, and pageRange, which turns it into an item range. Then test them with normal, edge and invalid input. Remember that in Next.js a searchParams value can be a string, an array of strings or undefined.
- Return 1 when ?page is missing
- Return 1 for invalid values such as "0", "-2", "abc" and "2.5"
- When the value is an array, as in ?page=2&page=5, use the first one
- Test that pageRange(3, 10) equals { start: 20, end: 30 }
// lib/pagination.ts
export function parsePage(value: string | string[] | undefined): number {
// TODO: take the first value if it is an array
// TODO: accept only whole numbers >= 1, otherwise return 1
return 1;
}
export function pageRange(page: number, pageSize: number) {
// TODO: return { start, end } for slicing the notes array
return { start: 0, end: 0 };
}
// TODO: paste the describe / it / expect stand-in from the lesson
// (or import them from "vitest" in a real project), adding a toBe matcher
// TODO: describe("parsePage", ...) with one it(...) per requirement
// TODO: describe("pageRange", ...)Expected: Four ✓ lines under parsePage and one under pageRange. If you remove the regex from parsePage, the "falls back to 1" test turns into a ✗.
Show hint
The regex /^\d+$/ accepts only strings made of digits, which rejects "-2" and "2.5" in one go. Then convert with Number() and check it is at least 1. A toBe matcher can be written with equal from node:assert.
Show solution
import { deepStrictEqual, equal } from "node:assert/strict";
// lib/pagination.ts
// searchParams values arrive as string | string[] | undefined.
export function parsePage(value: string | string[] | undefined): number {
const raw = Array.isArray(value) ? value[0] : value;
if (raw === undefined || !/^\d+$/.test(raw)) return 1;
const page = Number(raw);
return page >= 1 ? page : 1;
}
export function pageRange(page: number, pageSize: number) {
const start = (page - 1) * pageSize;
return { start, end: start + pageSize };
}
// Stand-in for: import { describe, expect, it } from "vitest";
const describe = (name: string, fn: () => void) => { console.log(name); fn(); };
const it = (name: string, fn: () => void) => {
try { fn(); console.log(` ✓ ${name}`); }
catch (err) { console.log(` ✗ ${name}: ${(err as Error).message}`); }
};
const expect = (actual: unknown) => ({
toBe: (expected: unknown) => equal(actual, expected),
toEqual: (expected: unknown) => deepStrictEqual(actual, expected),
});
describe("parsePage", () => {
it("defaults to page 1 when ?page is missing", () => {
expect(parsePage(undefined)).toBe(1);
});
it("reads a normal page number", () => {
expect(parsePage("3")).toBe(3);
});
it("falls back to 1 for zero, negatives and text", () => {
for (const bad of ["0", "-2", "abc", "2.5", ""]) expect(parsePage(bad)).toBe(1);
});
it("uses the first value of ?page=2&page=5", () => {
expect(parsePage(["2", "5"])).toBe(2);
});
});
describe("pageRange", () => {
it("turns page 3 of size 10 into items 20 to 30", () => {
expect(pageRange(3, 10)).toEqual({ start: 20, end: 30 });
});
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Use type checks, unit, component and E2E tests as layers, because each catches different bugs
- Pull rules out of Server Actions and pages into plain functions and test them quickly with Vitest
- Cover flows with async Server Components using Playwright E2E tests against a production build
- Server code logs to the terminal; client code logs to the browser console
Next.js — Testing — Next.js
Next.js — Testing — Next.js