Next.js applications are usually tested on two levels. Unit tests check individual components and functions quickly, typically with Vitest or Jest plus React Testing Library. End-to-end (E2E) tests open pages in a real browser and walk through user flows, typically with Playwright or Cypress. This chapter focuses on setting up and writing tests with Vitest and Playwright.
async Server Components are relatively new to the React ecosystem, and unit test runners such as Vitest and Jest cannot fully render them yet. The official docs therefore recommend covering them with E2E tests. If you extract the data-processing logic from such a component into plain functions, you can still unit test that part thoroughly.
Setting up Vitest
Install the packages as dev dependencies. vite-tsconfig-paths lets your tests resolve aliases such as @/.
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths
Create a config file at the project root and add a "test": "vitest" script to package.json.
// vitest.config.mts
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",
},
});
You can also start from an official example such as create-next-app --example with-vitest, which comes with this setup in place. If you prefer Jest, the next/jest helper configures SWC transforms, CSS and image imports, and environment variable loading for you.
Testing components
Render a Client Component such as the LikeButton from the previous chapter, click it like a user would, and assert on the result. React Testing Library encourages you to query by role and visible text rather than implementation details.
// app/ui/like-button.test.tsx
import { describe, expect, it } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { LikeButton } from "./like-button";
describe("LikeButton", () => {
it("increments the count on each click", () => {
render(<LikeButton initial={3} />);
const button = screen.getByRole("button");
fireEvent.click(button);
expect(button.textContent).toContain("4");
});
});
Components that call next/navigation hooks such as useRouter or usePathname need a mock, because the Next.js router does not exist in the test environment.
import { vi } from "vitest";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }),
usePathname: () => "/dashboard",
useSearchParams: () => new URLSearchParams("q=next"),
}));
E2E tests with Playwright
Playwright automates Chromium, Firefox and WebKit through one API. Its setup wizard creates a config file and example tests.
npm init playwright
With the webServer option, Playwright starts your Next.js server before the tests and waits until it is ready. For results closer to production, test a production build served by next start rather than the dev server.
// playwright.config.ts
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,
},
});
// e2e/navigation.spec.ts
import { expect, test } from "@playwright/test";
test("navigates from the home page to About", async ({ page }) => {
await page.goto("/");
await page.getByRole("link", { name: "About" }).click();
await expect(page).toHaveURL("/about");
await expect(page.getByRole("heading", { level: 1 })).toHaveText("About");
});
Run E2E tests with npx playwright test, or use npx playwright test --ui to step through each run visually. Flows that involve Server Actions, such as form submissions, are best verified this way, under realistic conditions.
Running tests in CI
A typical CI pipeline runs linting, type checking, unit tests, the build and then E2E tests. You can type-check separately with npx tsc --noEmit, and next build also reports type errors. Putting the fast steps first surfaces failures early.
Summary
- Unit test pure logic and Client Components with Vitest (or Jest) and React Testing Library.
- Cover
async Server Components and full user flows with an E2E tool such as Playwright. - Mock
next/navigation hooks in unit tests. - Run E2E tests against a server started with
next start after next build for production-like results.
0 comments
Sign in · Sign in to leave a comment.