Testing Next.js: Unit, Integration, and E2E
A Next.js application spans three runtimes, and each needs a different test style. Interactive components need DOM-level assertions that verify what the user sees. Server logic â route handlers, Server Actions, data modules â needs fast unit tests with the database faked. Whole flows across routes, cookies, and redirects need a real browser. Teams that pick one layer and stop usually discover the gap as a production incident: green unit suites beside a broken checkout, or slow end-to-end runs that nobody waits for.
This lesson lays out a practical test pyramid for the App Router. You will configure Jest with the Next.js environment, test client components the way React Testing Library intends, exercise Server Components and route handlers without spinning up a browser, and write Playwright specs that catch the navigation and cookie bugs only a real browser can.
Prerequisites
- !Comfort reading and writing React components
- !A working Next.js project you can run locally
- !Basic command-line usage of npm or pnpm scripts
What You'll Learn
- 1Configure Jest and React Testing Library for Next.js
- 2Test client components by role and behavior rather than implementation
- 3Unit test route handlers and Server Actions with fakes
- 4Write focused Playwright specs for multi-route flows
Configuration that matches the framework
Next.js works with Jest out of the box once you point the environment at jest-environment-jsdom for DOM tests and add the module alias for path imports. The next/jest preset handles the transform pipeline, CSS module stubs, and image imports so configuration stays small.
// jest.config.js
import nextJest from 'next/jest';
const createJestConfig = nextJest({ dir: './' });
const customJestConfig = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
},
testPathIgnorePatterns: [
'<rootDir>/node_modules/',
'<rootDir>/.next/',
'<rootDir>/e2e/',
],
};
export default createJestConfig(customJestConfig);
// jest.setup.js
import '@testing-library/jest-dom';
// next/navigation is heavily mocked in component tests
jest.mock('next/navigation', () => ({
useRouter: () => ({
push: jest.fn(),
replace: jest.fn(),
refresh: jest.fn(),
back: jest.fn(),
}),
usePathname: () => '/',
useSearchParams: () => new URLSearchParams(),
redirect: jest.fn(),
notFound: jest.fn(),
}));
Keep the mock surface honest: mock the router only where the component actually calls it, and prefer dependency injection so fewer globals need stubbing at all.
Client components: test what the user does
React Testing Library's philosophy is to interact the way a person would â by role, label, and visible text â and to avoid asserting on internal state or exact class names. That discipline survives refactors that restructure components without changing behavior.
// components/__tests__/quantity-picker.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import QuantityPicker from '../quantity-picker';
describe('QuantityPicker', () => {
it('increments and decrements within bounds', async () => {
const user = userEvent.setup();
render(<QuantityPicker min={1} max={5} onChange={jest.fn()} />);
const input = screen.getByLabelText('Quantity');
expect(input).toHaveValue(1);
await user.click(screen.getByRole('button', { name: 'Increase quantity' }));
expect(input).toHaveValue(2);
await user.click(screen.getByRole('button', { name: 'Decrease quantity' }));
await user.click(screen.getByRole('button', { name: 'Decrease quantity' }));
expect(input).toHaveValue(1); // never below min
});
it('disables increase at the maximum', async () => {
const user = userEvent.setup();
render(<QuantityPicker min={1} max={2} onChange={jest.fn()} />);
await user.click(screen.getByRole('button', { name: 'Increase quantity' }));
expect(screen.getByRole('button', { name: 'Increase quantity' })).toBeDisabled();
});
});
Async interactions need userEvent.setup() rather than raw fireEvent so timers and microtasks flush the way they do in a browser. If a test needs waitFor more than once, the component's async behavior deserves a second look before the test does.
Server logic without a browser
Route handlers are plain functions taking a Request, so unit tests do not need Next.js at all â construct a Request, call the handler, assert on the Response. Server Actions follow the same shape. The discipline is faking the boundary: swap the database module with a jest mock so tests stay fast and hermetic.
// app/api/products/__tests__/route.test.js
import { GET, POST } from '../route';
import { db } from '@/lib/db';
jest.mock('@/lib/db', () => ({
db: { product: { findMany: jest.fn(), create: jest.fn() } },
}));
describe('GET /api/products', () => {
it('returns a filtered list', async () => {
db.product.findMany.mockResolvedValue([{ id: '1', name: 'Desk lamp' }]);
const request = new Request('http://localhost/api/products?category=lighting');
const response = await GET(request);
const body = await response.json();
expect(response.status).toBe(200);
expect(body.products).toHaveLength(1);
expect(db.product.findMany).toHaveBeenCalledWith(
expect.objectContaining({ take: 20 })
);
});
});
describe('POST /api/products', () => {
it('rejects malformed bodies with 400', async () => {
const request = new Request('http://localhost/api/products', {
method: 'POST',
body: 'not-json',
});
const response = await POST(request);
expect(response.status).toBe(400);
});
it('returns 422 with issues for schema failures', async () => {
const request = new Request('http://localhost/api/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'x' }),
});
const response = await POST(request);
const body = await response.json();
expect(response.status).toBe(422);
expect(body.issues.length).toBeGreaterThan(0);
});
});
Testing the 400 and 422 branches catches more real bugs than the happy path ever does, because clients depend on those shapes for form error display.
End-to-end flows with Playwright
Playwright runs a real browser against the dev or production server, which makes it the only layer that exercises middleware redirects, cookie persistence, and full page navigation. Keep specs few and high-value: sign-in, a primary CRUD flow, and one checkout or submission path.
// e2e/auth.spec.js
import { test, expect } from '@playwright/test';
test('signs in and reaches the dashboard', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByLabel('Password').fill('correct-horse-battery');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/\/dashboard/);
await expect(page.getByRole('heading', { level: 1 })).toContainText('Welcome back');
});
test('redirects anonymous visitors away from settings', async ({ page }) => {
await page.goto('/settings');
await expect(page).toHaveURL(/\/login/);
});
Run these against a production build in CI â next build && next start â not only the dev server, so caching, middleware matcher differences, and bundle errors surface before users find them.
What each layer owns
| Layer | Target | Speed | Runs in CI on every PR |
|---|---|---|---|
| Unit (Jest) | Components, lib functions, actions | Milliseconds | Yes |
| Integration (Jest + RTL) | Pages with mocked data | Seconds | Yes |
| API (Jest) | Route handlers, middleware logic | Milliseconds | Yes |
| End to end (Playwright) | Multi-route flows, auth, payments | Minutes | On merge or nightly |
| Visual regression | Layout, RTL, fonts | Minutes | On merge |
The pyramid is not sacred, but the distribution is: many cheap tests, a moderate number of integration tests, and a handful of end-to-end specs that would catch a total outage. When end-to-end coverage grows until it dominates CI time, the fix is almost always to promote stable patterns into integration tests rather than to delete the browser layer.
Production pitfalls
The recurring problems: mocking fetch globally so route handler tests silently pass against stubs while the real API contract drifts; asserting on class names, so a Tailwind refactor breaks forty tests with zero behavior changes; and skipping the production build in CI, which lets middleware and server component errors slip through to deploy day. Another quiet one â tests that share a single database row without cleanup, producing order-dependent suites that fail only on the slowest machine.
Coverage that predicts production health
Line coverage is a poor proxy for confidence; a suite can cover every line of a route handler and still miss the case that takes the site down. Better targets are behavioral: every branch that returns a non-200 status, every redirect rule in middleware, every form validation message a user can trigger, and every permission check that guards data. Track those as explicit test cases rather than chasing a percentage, and review the list when an incident occurs â the postmortem question is always whether a test could have caught it, and the answer reshapes the suite more effectively than any coverage gate. Error paths deserve particular attention because they rot silently: a handler's 500 branch written at launch may reference an exception shape that a refactor changed six months later, and only a test asserting that branch keeps it honest. The same applies to components' empty and loading states, which are what users actually see when a dependency is slow and are therefore just as much a product surface as the happy path.
// components/__tests__/product-list-states.test.jsx
import { render, screen } from '@testing-library/react';
import ProductList from '../product-list';
describe('ProductList states', () => {
it('renders a skeleton while loading', () => {
render(<ProductList loading products={[]} />);
expect(screen.getByTestId('product-skeleton')).toBeInTheDocument();
});
it('shows an empty state with a next action', () => {
render(<ProductList loading={false} products={[]} />);
expect(screen.getByRole('heading', { name: /no products yet/i })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /create your first/i })).toBeInTheDocument();
});
it('renders rows for provided products', () => {
render(
<ProductList
loading={false}
products={[
{ id: '1', name: 'Desk lamp', price: '$40' },
{ id: '2', name: 'Standing mat', price: '$80' },
]}
/>
);
expect(screen.getByText('Desk lamp')).toBeInTheDocument();
expect(screen.getByText('Standing mat')).toBeInTheDocument();
});
});
Wiring the suite into continuous integration
A test suite that does not run in CI does not exist. The practical wiring is a fast lane and a slow lane: Jest runs on every pull request in a separate job, Playwright runs on merge to the main branch or nightly against a production build, and both post their results where the team already looks. Cache the dependency install and the Next.js build between jobs so the fast lane stays under a few minutes; a suite that takes twenty minutes gets bypassed under deadline pressure, which is worse than a smaller suite that never gets skipped. Flaky tests need a policy too: quarantine them with a linked issue and a deadline rather than silently retrying, because silent retries train the team to ignore red. When the fast lane goes red on a pull request, the author should be able to reproduce the failure locally with one command â document that command in the repository README and keep its output readable, because the goal is not coverage for its own sake; it is a team that trusts the suite enough to ship on green.
Common Mistakes
Asserting on className strings in component tests
Fix: Query by role, label, and text; reserve class assertions for genuinely visual contracts tested in visual regression.
Mocking fetch globally for every test file
Fix: Mock at the module boundary your code imports â the data layer or the database â so handler logic still executes realistically.
Running end-to-end tests only against the dev server
Fix: Run the suite against next build && next start in CI to catch build-time and caching issues.
Sharing mutable fixtures across test files
Fix: Seed and clean data per test or per file so suites stay order-independent.
Best Practices
- Use next/jest so transforms and asset mocks stay aligned with the framework
- Test route handlers as plain functions with constructed Request objects
- Limit Playwright specs to flows whose failure means lost revenue or trust
- Fail CI on new console errors from the app under test; they predict real bugs
Interview Questions
Q1: Why test route handlers without rendering a page?
They are pure Request-to-Response functions; constructing a Request in Jest exercises validation, status codes, and headers in milliseconds with no browser involved.
Q2: What does next/jest provide?
A factory that preconfigures SWC transforms, CSS module handling, image imports, and path aliases so the Jest config only adds your project-specific options.
Q3: When is Playwright the right tool rather than Jest?
When the behavior depends on a real browser or full stack: middleware redirects, cookie flows, multi-page navigation, and anything involving actual network requests to your server.
Key Takeaways
- Match the test style to the runtime: RTL for client components, plain function tests for server logic, Playwright for flows.
- next/jest keeps configuration minimal and aligned with the framework's build pipeline.
- Query by role and label so tests survive refactors; mock at module boundaries, not globally.
- Run end-to-end specs against a production build so caching and middleware bugs surface in CI.
- Keep the end-to-end layer small and high-value, and promote stable patterns into faster tests.