Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Testing Next.js: Vitest for Server Components and Playwright for the Rest

Async Server Components cannot render in jsdom, so awaiting the component is the unit test and a real browser is the integration test. What each layer actually proves.

~4 min readNext.js
#Next.js#Testing#Vitest#Playwright
3D illustration of a test pyramid with a browser window running an end-to-end test

Quick Summary

Server Components broke the default assumption of the React testing ecosystem: they are async, they never run in jsdom, and libraries such as React Testing Library cannot render them. A test that "renders the page" will fail with async/await is not yet supported in Client Components or silently return a promise as a child.

The workable split is three layers. Vitest covers pure logic and client components with jsdom. Async Server Components are tested by awaiting them and inspecting the returned tree, or by testing the data functions they call. Playwright covers the behaviour that only exists in a real browser with a real server: streaming, navigation, cookies, redirects, and Server Actions.

Playwright needs a production build (next build then next start) for the things Next.js does differently in dev — prefetching, cache headers, prerendering — but next dev is faster and auto-reloads. Use dev for iteration and one production run in CI.

Basic Syntax & Core Signatures

ts
// vitest.config.ts import { defineConfig } from "vitest/config"; import react from "@vitejs/plugin-react"; import tsconfigPaths from "vite-tsconfig-paths"; export default defineConfig({ plugins: [react(), tsconfigPaths()], test: { environment: "jsdom", setupFiles: ["./vitest.setup.ts"], globals: true, exclude: ["e2e/**", "node_modules/**"], }, });
ts
// vitest.setup.ts — the mocks every App Router component needs import "@testing-library/jest-dom/vitest"; import { vi } from "vitest"; vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn(), back: vi.fn() }), usePathname: () => "/dashboard", useSearchParams: () => new URLSearchParams("tab=open"), useParams: () => ({ slug: "hello" }), redirect: vi.fn((url: string) => { throw new Error(`NEXT_REDIRECT:${url}`); }), notFound: vi.fn(() => { throw new Error("NEXT_NOT_FOUND"); }), }));
ts
// app/components/counter.test.tsx — client component, normal RTL import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { Counter } from "./counter"; test("increments", async () => { render(<Counter start={0} />); await userEvent.click(screen.getByRole("button", { name: /increment/i })); expect(screen.getByText("1")).toBeInTheDocument(); });
ts
// app/blog/[slug]/page.test.tsx — async Server Component, awaited directly import { render, screen } from "@testing-library/react"; import Page, { generateMetadata } from "./page"; vi.mock("@/lib/posts", () => ({ getPost: vi.fn(async () => ({ title: "Hello", body: "World" })), })); test("renders the post title", async () => { const ui = await Page({ params: Promise.resolve({ slug: "hello" }) }); render(ui); // the resolved tree is plain React elements expect(screen.getByRole("heading", { name: "Hello" })).toBeInTheDocument(); });
ts
// playwright.config.ts import { defineConfig, devices } from "@playwright/test"; export default defineConfig({ testDir: "./e2e", fullyParallel: true, use: { baseURL: "http://127.0.0.1:3000", trace: "on-first-retry" }, webServer: { command: "npm run build && npm run start", url: "http://127.0.0.1:3000", reuseExistingServer: !process.env.CI, timeout: 180_000, }, projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }], });

Key Comparison Table

ApproachAsync Server ComponentsStreaming / SuspenseCookies and authSpeed
Vitest + RTL (jsdom)Only by awaiting manuallyNoMockedFastest
Vitest + renderToStaticMarkupYes, awaitedPartlyMockedFast
Vitest browser modeYes, awaitedPartlyMockedMedium
Playwright E2EYes, real serverYesRealSlowest, highest fidelity
Storybook + test-runnerNo for async SC without workaroundsNoMockedMedium
What you are testingBest toolWhy
Formatting, validation, reducersVitest, no DOMPure functions need no renderer
Client component interactionsVitest + RTL + user-eventFast feedback, accessible queries
Server component output for given dataVitest, await the componentData can be mocked at the module boundary
Server Action end to endPlaywrightNeeds a real request and cookie jar
Redirect and cookie semanticsPlaywrightredirect() throws; assertions need the network
Visual layout and thumbnailsPlaywright screenshotsPixels need a browser

Practical Edge Cases & Deep Dives

1. Why RTL cannot render an async component

render(<Page />) produces the error A component suspended while responding to synchronous input or a promise child, because jsdom has no React Server Component runtime. Awaiting the function yourself sidesteps it: const ui = await Page({ params: Promise.resolve(...) }) gives you the element tree that the server would have rendered, and RTL can then render that tree — as long as the tree contains no further async components. Nested async components need to be awaited the same way, which is why testing at the page boundary is more practical than deep trees.

2. redirect() and notFound() throw — assert the throw

Both raise special errors that Next.js catches. In a unit test they surface as thrown errors, so the assertion is on rejects.toThrow, not on rendered output:

ts
import { redirect } from "next/navigation"; test("redirects anonymous users", async () => { vi.mocked(getSession).mockResolvedValue(null); await expect(Dashboard()).rejects.toThrow(/NEXT_REDIRECT/); expect(redirect).toHaveBeenCalledWith("/login"); });

The mock in vitest.setup.ts must actually throw; a vi.fn() that returns undefined lets execution continue and produces a false pass.

3. Mocking the network at the HTTP boundary

Mocking your own data module couples the test to the module path and hides real query behaviour. msw intercepts fetch, so the same handler serves Vitest and Playwright, and the test exercises the parse and error branches:

ts
// mocks/handlers.ts import { http, HttpResponse } from "msw"; export const handlers = [ http.get("https://api.example.com/posts/:slug", ({ params }) => HttpResponse.json({ slug: params.slug, title: "Hello", body: "World" })), ];

In the App Router the fetch that runs inside a Server Component does execute under Vitest if you call the component directly, so msw works there. Inside a Server Action invoked from a client component, it does not — that path needs Playwright.

4. Server Action coverage without a browser

A Server Action is a plain exported async function, so it can be called directly with a FormData. That covers validation, database calls, and revalidateTag, but not the parts that need a request context: cookies(), headers(), and redirect(). Stub next/headers and assert the calls:

ts
vi.mock("next/headers", () => ({ cookies: () => ({ get: vi.fn(), set: vi.fn(), delete: vi.fn() }), headers: () => new Headers({ "x-forwarded-for": "127.0.0.1" }), })); test("rejects a short password", async () => { const fd = new FormData(); fd.set("email", "a@b.co"); fd.set("password", "short"); const result = await signIn(null, fd); expect(result).toEqual({ error: "Invalid input" }); });

5. Playwright against a production build

next dev compiles on demand, so the first navigation in a test can exceed the default timeout and hide real regressions in prerendering. Running next build && next start in webServer catches build-time failures too — a page that only breaks when statically rendered fails in CI before any test runs. Set a long timeout for the web server (builds of a large site take minutes) and prefer reuseExistingServer locally.

For authenticated flows, seed the session with a storageState produced once by a setup project rather than logging in through the UI on every test.

ts
// e2e/auth.setup.ts import { test as setup } from "@playwright/test"; setup("authenticate", async ({ page }) => { await page.goto("/login"); await page.getByLabel("Email").fill("test@example.com"); await page.getByLabel("Password").fill(process.env.TEST_PASSWORD!); await page.getByRole("button", { name: "Sign in" }).click(); await page.waitForURL("/dashboard"); await page.context().storageState({ path: "e2e/.auth/user.json" }); });

6. Time, randomness, and hydration mismatches

A component that formats new Date() during render produces a different string on the server and the client, which React reports as a hydration error — and a test that mocks Date only on the client will not catch it. Freeze time with vi.useFakeTimers().setSystemTime(...) before rendering, and in Playwright assert on the rendered text rather than on the client clock.

Common Runtime & Configuration Mistakes

SymptomCauseFix
"async/await is not yet supported" in RTLAsync component passed to renderAwait the component first, render the resolved tree
Test passes while the app redirectsredirect mock returns instead of throwingThrow NEXT_REDIRECT in the mock
useSearchParams() error in a unit testComponent expects a Suspense boundaryWrap in <Suspense>, or mock the hook
Playwright times out on first testnext dev compiling on demandUse a production build, raise the web server timeout
Cookie set in a test does not reach the actionTest called the action directly, no request contextAssert against Playwright for cookie behaviour
Hydration warning only in E2EServer and client render different time or localeFreeze time, or render the formatted value on the server only
next/font throws under VitestFont loader needs the Next.js compilerMock next/font/* in the setup file

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.