Testing Next.js Pages: Unit, Integration, and E2E
Most Next.js test suites fail in one of two directions. Either they render nothing but pure functions, giving a green pipeline that never once exercised a page, or they drive a full browser through every flow, giving a suite so slow and flaky that people stop reading the failures. The useful middle ground is decided by a single question per test: what is the cheapest way to prove this behaviour still works?
This lesson maps that question onto an App Router project â which layer owns which bug, how to render a client component without a browser, how to test a server component or a route handler without pretending you are testing React, and where a real browser is genuinely unavoidable.
Prerequisites
- !React components and hooks
- !Async JavaScript and promises
- !A Next.js project with a passing next build
What You'll Learn
- 1Assign each defect type to the layer that catches it cheapest
- 2Write component tests with testing-library queries and user events
- 3Test route handlers by calling them as functions
- 4Run Playwright against a production build to catch build-only bugs
The pyramid, translated to the App Router
Every layer exists to catch a class of bug the layer below cannot see, and each one costs roughly an order of magnitude more than the one below it. Spending effort in the wrong place shows up as either a slow suite or a blind spot.
| Layer | Catches | Runs | Cost per test |
|---|---|---|---|
| Unit | Logic errors, formatting, branching | Milliseconds, no DOM | Very low |
| Component | Rendering, interaction, accessibility | jsdom, no network | Low |
| Route handler | Status codes, auth, validation | Node, mocked data | Low |
| Integration (page level) | Data flow between components | jsdom or light server | Medium |
| End to end | Routing, builds, real network, third parties | Full browser | High |
The rule that keeps a suite healthy is that a bug belongs to the lowest layer that could have caught it. A wrong currency format is a unit test. A button that does not call its handler is a component test. A page that works in development and 500s after next build is an end-to-end test, and no amount of unit coverage substitutes for it.
Unit tests for the logic you would otherwise debug in a browser
Pure functions are the cheapest thing you own: they take values and return values, so a test is a table of inputs and expectations with nothing to wire up. The payoff is not coverage percentage â it is that refactoring these functions stops being scary.
// lib/__tests__/pricing.test.js
import { formatPrice, applyDiscount, priceRange } from '../pricing';
describe('formatPrice', () => {
it('formats minor units into a decimal currency string', () => {
expect(formatPrice(1999, 'USD')).toBe('$19.99');
expect(formatPrice(50, 'EUR')).toBe('âŦ0.50');
});
it('never renders more than two decimals', () => {
expect(formatPrice(19995, 'GBP')).toBe('ÂŖ199.95');
});
});
describe('applyDiscount', () => {
it('is idempotent for a 100 percent discount', () => {
const once = applyDiscount(4000, 100);
expect(applyDiscount(once, 100)).toBe(0);
});
it('rejects a discount above 100 percent instead of producing a negative price', () => {
expect(() => applyDiscount(4000, 150)).toThrow(/discount/i);
});
});
describe('priceRange', () => {
it('sorts prices regardless of input order', () => {
expect(priceRange([300, 100, 200])).toEqual({ min: 100, max: 300 });
});
it('returns null for an empty catalogue', () => {
expect(priceRange([])).toBeNull();
});
});
The most valuable assertions here are the awkward ones: the empty input, the boundary value, the case the function is not supposed to handle. Happy-path tests pass forever and teach nothing at review time.
Component tests that query like a user
A component test should fail when the visible behaviour changes, not when the implementation is refactored. That means querying by role, label, and text rather than by class name or test id, and driving interactions through user events so the sequence of keystrokes and clicks is realistic.
// components/__tests__/signup-form.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SignupForm } from '../signup-form';
describe('SignupForm', () => {
it('submits valid input and reports success', async () => {
const user = userEvent.setup();
const onSubmit = jest.fn().mockResolvedValue({ ok: true });
render(<SignupForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/email address/i), 'ada@example.com');
await user.type(screen.getByLabelText(/password/i), 'correct horse battery');
await user.click(screen.getByRole('button', { name: /create account/i }));
expect(onSubmit).toHaveBeenCalledWith({
email: 'ada@example.com',
password: 'correct horse battery',
});
expect(await screen.findByRole('status')).toHaveTextContent(/account created/i);
});
it('blocks submission and explains why when the email is missing', async () => {
const user = userEvent.setup();
const onSubmit = jest.fn();
render(<SignupForm onSubmit={onSubmit} />);
await user.click(screen.getByRole('button', { name: /create account/i }));
expect(onSubmit).not.toHaveBeenCalled();
expect(await screen.findByRole('alert')).toHaveTextContent(/enter your email/i);
});
});
findByRole waits, getByRole does not â using the waiting variant for anything that appears after state changes removes the majority of timing flakiness people blame on jsdom. Asserting that the handler was not called is just as important as asserting that it was: it proves the validation actually gates the submission rather than merely displaying a message.
Testing handlers by calling them directly
Route handlers are plain functions taking a Request and returning a Response, which means no server, no port, and no HTTP client is required to test them. Construct the request, await the handler, assert on status and body.
// app/api/posts/__tests__/route.test.js
import { GET, POST } from '../route';
import { db } from '@/lib/db';
jest.mock('@/lib/db', () => ({
db: { post: { findMany: jest.fn(), create: jest.fn() } },
}));
function jsonRequest(method, body, headers = {}) {
return new Request('http://localhost/api/posts', {
method,
headers: { 'Content-Type': 'application/json', ...headers },
body: body ? JSON.stringify(body) : undefined,
});
}
describe('POST /api/posts', () => {
it('rejects an unauthenticated request with 401', async () => {
const res = await POST(jsonRequest('POST', { title: 'Hi', body: 'Text' }));
expect(res.status).toBe(401);
expect(db.post.create).not.toHaveBeenCalled();
});
it('returns field errors with 400 when validation fails', async () => {
const res = await POST(
jsonRequest('POST', { title: '', body: '' }, { authorization: 'Bearer valid' })
);
expect(res.status).toBe(400);
const payload = await res.json();
expect(payload.errors).toHaveProperty('title');
});
it('creates a post scoped to the session user', async () => {
db.post.create.mockResolvedValue({ id: 'p1' });
const res = await POST(
jsonRequest('POST', { title: 'Ship it', body: 'Details' }, { authorization: 'Bearer valid' })
);
expect(res.status).toBe(201);
expect(db.post.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ authorId: 'user-1' }) })
);
});
});
Mock the data layer, not the database driver. Keeping the fake at the boundary you own means the test still exercises your query construction, your filtering, and your status mapping â the parts where bugs actually live.
Browser tests against a production build
Some failures exist only after a build: a client component imported by a server file, a missing environment variable that is inlined at compile time, a static page generated with undefined data, a broken relative asset path. Unit and component tests run through a development transform and will never see any of them, so the end-to-end suite must run next build && next start.
// e2e/checkout.spec.js
import { test, expect } from '@playwright/test';
test.describe('checkout', () => {
test('completes a purchase end to end', async ({ page }) => {
await page.goto('/products/blue-mug');
await expect(page.getByRole('heading', { level: 1 })).toHaveText('Blue Mug');
await page.getByRole('button', { name: /add to cart/i }).click();
await page.goto('/checkout');
await expect(page.getByText(/blue mug/i)).toBeVisible();
await page.getByLabel(/card number/i).fill('4242 4242 4242 4242');
await page.getByRole('button', { name: /pay/i }).click();
await expect(page.getByRole('status')).toHaveText(/order confirmed/i);
await expect(page).toHaveURL(/\/orders\/[a-z0-9-]+/);
});
test('returns 404 for a deleted product', async ({ request }) => {
const res = await request.get('/products/does-not-exist');
expect(res.status()).toBe(404);
});
});
Keep the suite small and high-value: the critical path a business depends on, plus a handful of smoke checks on every deploy. Authentication, payment, and data-integrity flows earn browser tests; a colour change does not. And run them against the built output in continuous integration, because that is the artefact your users receive.
Fixtures, isolation, and keeping the suite fast
A suite that takes twenty minutes gets run by nobody, and almost all of that time comes from two avoidable sources: fixtures that are large and hand-written, and tests that depend on each other's leftovers. Both have the same cure â build objects from a factory with sensible defaults, and make every test create its own world.
// test/factories.js
let counter = 0;
export function makeUser(overrides = {}) {
counter += 1;
return {
id: `user-${counter}`,
email: `person${counter}@example.test`,
role: 'member',
createdAt: new Date('2026-01-01T00:00:00Z'),
...overrides,
};
}
export function makePost(overrides = {}) {
counter += 1;
return {
id: `post-${counter}`,
title: `Post ${counter}`,
body: 'Body text for the test.',
published: true,
author: makeUser(),
...overrides,
};
}
Explicit timestamps and deterministic ids are not pedantry: a test that asserts on ordering will pass today and fail on the machine with a different clock, and a test that asserts on a random id will never be reproducible when it fails in continuous integration. Give the factory fixed defaults and let individual tests override only the field they care about, which keeps the intent of each assertion readable three months later.
Isolation follows the same logic. Reset mocks in beforeEach, use a unique schema or a transaction that rolls back for anything touching a database, and never let one test's mutation remain visible to the next â a suite that passes when run alone and fails when run in parallel is telling you about shared state rather than about your code. Avoid broad snapshot assertions for the same reason: a snapshot of an entire rendered page breaks on an unrelated copy change and teaches reviewers to press the update button without reading the diff. Snapshot the small, stable fragments â a serialised API payload, a single component â where a change really is a decision.
The last lever is what runs in which job. Keep unit and component tests in the pull-request loop so feedback arrives in a minute or two, and move the browser suite to a merge or nightly job if it cannot finish in the same window. The goal is not fewer tests; it is a suite whose failures arrive while the author still remembers the change.
Common Mistakes
Writing unit tests for everything and calling the suite complete
Fix: Add at least one browser test per critical flow; only a real build exposes bundling and runtime errors.
Querying by class name or test id when a role exists
Fix: Use getByRole and getByLabelText so a class rename or a styling refactor cannot break the test.
Mocking the module you are trying to verify
Fix: Mock at the system boundary â the data layer or the network â not the function under test.
Asserting only the happy path
Fix: Include the empty, invalid and unauthorized branches; they are where regressions hide.
Running the browser suite against the dev server
Fix: Build and start the production output so build-time inlining and static generation are covered.
Best Practices
- Put each test in the cheapest layer that could catch the defect
- Derive fixtures from a factory function so a field addition updates one place
- Prefer waiting queries over arbitrary sleeps â sleeps are the main source of flake
- Fail continuous integration on any test failure for the default branch
Key Takeaways
- Assign bugs to the lowest layer that can catch them; pay more only where a cheaper layer is blind.
- Component tests should query by role and label so they survive refactoring.
- Route handlers are functions: call them with a Request and assert on the Response.
- Mock the data layer, not the internals under test, so real logic still executes.
- Run a small end-to-end suite against a production build to catch what only a build reveals.