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.

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
// 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/**"],
},
});// 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"); }),
}));// 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();
});// 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();
});// 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
| Approach | Async Server Components | Streaming / Suspense | Cookies and auth | Speed |
|---|---|---|---|---|
| Vitest + RTL (jsdom) | Only by awaiting manually | No | Mocked | Fastest |
Vitest + renderToStaticMarkup | Yes, awaited | Partly | Mocked | Fast |
| Vitest browser mode | Yes, awaited | Partly | Mocked | Medium |
| Playwright E2E | Yes, real server | Yes | Real | Slowest, highest fidelity |
| Storybook + test-runner | No for async SC without workarounds | No | Mocked | Medium |
| What you are testing | Best tool | Why |
|---|---|---|
| Formatting, validation, reducers | Vitest, no DOM | Pure functions need no renderer |
| Client component interactions | Vitest + RTL + user-event | Fast feedback, accessible queries |
| Server component output for given data | Vitest, await the component | Data can be mocked at the module boundary |
| Server Action end to end | Playwright | Needs a real request and cookie jar |
| Redirect and cookie semantics | Playwright | redirect() throws; assertions need the network |
| Visual layout and thumbnails | Playwright screenshots | Pixels 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:
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:
// 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:
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.
// 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
| Symptom | Cause | Fix |
|---|---|---|
| "async/await is not yet supported" in RTL | Async component passed to render | Await the component first, render the resolved tree |
| Test passes while the app redirects | redirect mock returns instead of throwing | Throw NEXT_REDIRECT in the mock |
useSearchParams() error in a unit test | Component expects a Suspense boundary | Wrap in <Suspense>, or mock the hook |
| Playwright times out on first test | next dev compiling on demand | Use a production build, raise the web server timeout |
| Cookie set in a test does not reach the action | Test called the action directly, no request context | Assert against Playwright for cookie behaviour |
| Hydration warning only in E2E | Server and client render different time or locale | Freeze time, or render the formatted value on the server only |
next/font throws under Vitest | Font loader needs the Next.js compiler | Mock next/font/* in the setup file |
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.