Publicado · en mejora
Guía de Next.js · 5/6
Por ahora, este capítulo solo está disponible en inglés.
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.
| Target | Recommended tools | Why |
|---|---|---|
| Pure functions, validation, data transforms | Vitest or Jest | Fast, no browser needed |
| Client Components, synchronous Server Components | Vitest or Jest with React Testing Library | Checks rendered output and interactions |
async Server Components, routing, Server Action flows | Playwright or Cypress | Exercises the real server and browser |
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.
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-pathsCreate 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.
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"),
}));Playwright automates Chromium, Firefox and WebKit through one API. Its setup wizard creates a config file and example tests.
npm init playwrightWith 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.
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.
async Server Components and full user flows with an E2E tool such as Playwright.next/navigation hooks in unit tests.next start after next build for production-like results.
0 comentarios
Iniciar sesión · Inicia sesión para dejar un comentario.
Sé el primero en comentar.