FE·26
Frontend Testing
Building confidence in UI code: the testing trophy, unit, component, integration and E2E tests, visual regression, accessibility and performance testing, contract tests with the backend, plus the tools: Vitest/Jest, Testing Library, Playwright, Cypress, fixtures, mocking, network interception and traces.
Start here: testing frontends with confidence
Why test at all
A test is a small program that runs your code and checks it did the right thing. You write tests not to prove code is perfect but to change it without fear: when you refactor the cart next month, upgrade React, or a teammate edits a component they don't know, the tests tell you within seconds whether anything a user relies on broke. Without them, every change needs manual clicking through the app, so people stop changing things, and the code rots.
Every test has the same three steps, often called Arrange, Act, Assert:
it("adds a new dish with quantity 1", () => {
const s = cart(initial, { type: "added", dish: dosa }); // arrange + act: put the code in a known state, do the thing
expect(s.lines).toEqual([{ ...dosa, qty: 1 }]); // assert: check the outcome
});
Three levels of test
| Level | What it runs | Speed | Catches | Example |
|---|---|---|---|---|
| Unit | one function or module, no browser | milliseconds | logic errors | the cart reducer, a price formatter |
| Component / integration | components rendered into a simulated DOM (jsdom), network mocked | tens to hundreds of ms | UI behaviour, wiring between pieces | "typing an item and pressing Enter adds it to the list" |
| End-to-end (E2E) | the real app in a real browser, often a real backend | seconds | integration, routing, the build, browser quirks | "a shopper builds a list and checks out" |
Fast tests give quick feedback but miss problems between pieces; slow tests are realistic but costly and more fragile. A healthy frontend suite has many unit and component tests and a handful of E2E tests covering the critical user journeys (log in, search, pay). Many teams describe the ideal shape as a "testing trophy": the most value comes from component/integration tests, because that's where most frontend bugs live.
A unit test: the cart reducer
The reducer from chapter 25 is pure, so testing it needs no browser and no mocks:
import { describe, it, expect } from "vitest";
import { cart, initial, total } from "./cart.js";
const dosa = { id: 1, name: "Masala dosa", price: 90 };
const idli = { id: 2, name: "Idli", price: 50 };
describe("cart reducer", () => {
it("increments quantity when the same dish is added again", () => {
const s = [dosa, idli, dosa].reduce((st, d) => cart(st, { type: "added", dish: d }), initial);
expect(s.lines.map(l => [l.name, l.qty])).toEqual([["Masala dosa", 2], ["Idli", 1]]);
});
it("never mutates the previous state", () => {
const before = cart(initial, { type: "added", dish: dosa });
const frozen = structuredClone(before);
cart(before, { type: "added", dish: dosa });
expect(before).toEqual(frozen);
});
it.each([
["an empty cart", [], null, 0],
["one dosa", [dosa], null, 90],
["2 dosa + 1 idli with CHAI10", [dosa, dosa, idli], "CHAI10", 207],
["one dosa with an unknown coupon", [dosa], "WRONG", 90],
])("total of %s", (_label, dishes, coupon, expected) => {
let s = dishes.reduce((st, d) => cart(st, { type: "added", dish: d }), initial);
if (coupon) s = cart(s, { type: "couponApplied", code: coupon });
expect(total(s)).toBe(expected);
});
});
$ npx vitest run --reporter=verbose
✓ src/cart.test.js > cart reducer > increments quantity when the same dish is added again 0ms
✓ src/cart.test.js > cart reducer > never mutates the previous state 0ms
✓ src/cart.test.js > cart reducer > total of an empty cart 0ms
✓ src/cart.test.js > cart reducer > total of one dosa 0ms
✓ src/cart.test.js > cart reducer > total of 2 dosa + 1 idli with CHAI10 0ms
✓ src/cart.test.js > cart reducer > total of one dosa with an unknown coupon 0ms
it.each runs one test per row of a table: the cheapest way to cover edge cases (empty, one, many, invalid input).
A component test: test what the user sees and does
Testing Library renders a component into jsdom (a simulated DOM in Node) and finds elements the way users do: by their label, role and visible text, never by CSS classes or component internals. user-event simulates real typing and clicking:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ShoppingList } from "./ShoppingList.jsx";
it("adds items and counts the ones not done", async () => {
const user = userEvent.setup();
render(<ShoppingList />);
await user.type(screen.getByLabelText("New item"), "Toor dal{Enter}"); // find inputs the way users do: by label
await user.type(screen.getByLabelText("New item"), "Jaggery");
await user.click(screen.getByRole("button", { name: "Add" }));
expect(screen.getAllByRole("listitem")).toHaveLength(2);
expect(screen.getByRole("status")).toHaveTextContent("2 items left");
await user.click(screen.getByRole("button", { name: "Done: Toor dal" }));
expect(screen.getByRole("status")).toHaveTextContent("1 item left");
expect(screen.getByLabelText("New item")).toHaveValue(""); // the field was cleared
});
Because it never mentions useState, class names or the component's structure, this test keeps passing if you rewrite the component with a reducer, Zustand or even a different framework, as long as the user's experience is the same. And querying by label and role doubles as an accessibility check (chapter 20): if the test can't find "New item" by its label, a screen reader can't either.
Reading a failure
Introduce a bug (the counter counts all items instead of the ones not done) and run the tests again:
FAIL src/ShoppingList.test.jsx > adds items and counts the ones not done
Error: expect(element).toHaveTextContent()
Expected element to have text content:
1 item left
Received:
2 items left
❯ src/ShoppingList.test.jsx:19:38
18| expect(screen.getByRole("button", { name: "Done: Toor dal" })).toHav…
19| expect(screen.getByRole("status")).toHaveTextContent("1 item left");
| ^
A good failure tells you what the user would have seen wrong ("2 items left" instead of "1"), where in the test, and nothing about implementation. Read failures from the top: which test, what was expected, what was received, which line.
Faking the network with MSW
Components that fetch data need predictable responses in tests, including errors that are hard to trigger for real. Mock Service Worker (MSW) intercepts requests at the network level, so the component's code is unchanged:
const server = setupServer(
http.get("*/api/menu", () => HttpResponse.json([{ id: 1, name: "Masala dosa", price: 90 }, { id: 2, name: "Idli", price: 50 }])),
);
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it("shows an error and recovers on retry", async () => {
let calls = 0;
server.use(http.get("*/api/menu", () => (++calls === 1 ? new HttpResponse(null, { status: 503 }) : HttpResponse.json([{ id: 3, name: "Vada", price: 40 }]))));
render(<MenuPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load the menu (HTTP 503)");
await userEvent.click(screen.getByRole("button", { name: "Try again" }));
expect(await screen.findByText("Vada — ₹40")).toBeInTheDocument();
});
Note findBy… (which waits for the element to appear) for anything that happens after a network response, versus getBy… for what's already there.
An end-to-end test in a real browser
Playwright drives real Chromium, Firefox and WebKit. A test of the built app:
import { test, expect } from "@playwright/test";
test("a shopper builds a list with the keyboard", async ({ page }) => {
await page.goto("/");
const input = page.getByLabel("New item");
await input.fill("Rice (5 kg)");
await input.press("Enter");
await input.fill("Toor dal");
await page.getByRole("button", { name: "Add" }).click();
await expect(page.getByRole("listitem")).toHaveCount(2); // auto-waits until true (or times out)
await page.getByRole("button", { name: "Done: Rice (5 kg)" }).click();
await expect(page.getByRole("status")).toHaveText("1 item left");
});
Running 1 test using 1 worker
✓ 1 e2e/shopping.spec.js:3:1 › a shopper builds a list with the keyboard (884ms)
1 passed (3.2s)
The same role-and-label style as Testing Library, but now through the real build, the real browser and real events. Playwright's assertions retry until they pass or time out, which is what makes E2E tests reliable (the lab shows the alternative).
How deep to go in frontend testing
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name test levels, runners and tools; read a test and its failure |
| L2 | Write unit, component (Testing Library + MSW) and E2E (Playwright) tests for real features |
| L3 | Explain test doubles, isolation, auto-waiting, fixtures, what to test at which level, and coverage vs mutation score |
| L4 | Diagnose flaky tests with traces, eliminate timing dependence, find gaps with mutation testing |
| L5 | Design a test strategy and CI pipeline for a product: levels, contracts, visual and accessibility checks |
| L6 | Run testing at scale: sharding, quarantine, flake budgets, test data management, cost and speed of CI |
Strategy
What to test and why
Tests exist to give you confidence to change code. In frontends that means confidence that users can complete their tasks, that components behave correctly in edge states (loading, empty, error, long text, slow networks), and that a refactor didn't break anything. Two principles shape modern frontend testing:
- Test behaviour, not implementation. "The more your tests resemble the way your software is used, the more confidence they can give you" (Kent C. Dodds). A test that clicks "Add to cart" and checks the badge says "1" survives a refactor from Redux to Zustand. A test that asserts
store.dispatchwas called with an action object doesn't. - Put most of your effort where the confidence-to-cost ratio is best. For UIs, that's usually integration-style component tests, plus a thin layer of E2E tests for critical journeys.
The testing trophy (Dodds) adapts the classic testing pyramid to frontends:
| Layer | What it checks | Speed | Typical tools |
|---|---|---|---|
| Static | Types, lint rules (hooks rules, a11y lint), formatting | Instant | TypeScript, ESLint, Biome |
| Unit | Pure functions: formatting, reducers, validators, selectors, utilities | ms | Vitest, Jest |
| Component | One component in isolation: rendering states, interactions, a11y | 10s of ms | Testing Library + Vitest/Jest (jsdom), Vitest browser mode, Playwright component testing, Storybook interaction tests |
| Integration | Several components + state + routing + (mocked) network working together | 100s of ms | Testing Library + MSW |
| E2E | The whole deployed app in a real browser against a real or staged backend | Seconds | Playwright, Cypress |
| Visual regression | Pixels didn't change unexpectedly | Seconds | Playwright screenshots, Chromatic, Percy, Lost Pixel |
| Accessibility | axe rules, keyboard paths | Fast–medium | axe-core, Playwright |
| Performance | Budgets, Lighthouse scores, Web Vitals | Medium | Lighthouse CI, Playwright traces |
| Contract | Frontend's expectations of the API match what the backend provides | Fast | Pact, OpenAPI validation |
Test levels
Unit tests
Unit tests suit pure logic with many cases. Make UI code testable by pulling logic out of components into pure functions (reducers, validators, formatters, selectors):
// cart.ts
export function cartTotal(items: { price: number; qty: number }[], discountPct = 0) {
const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
return Math.round(subtotal * (1 - discountPct / 100)); // integer minor units (Vol. 1 ch. 6)
}
// cart.test.ts (Vitest: Jest-compatible API, Vite-powered, native ESM and TypeScript)
import { describe, it, expect } from "vitest";
import { cartTotal } from "./cart";
describe("cartTotal", () => {
it("sums price × qty", () => expect(cartTotal([{ price: 250, qty: 2 }, { price: 100, qty: 1 }])).toBe(600));
it("applies a percentage discount and rounds", () => expect(cartTotal([{ price: 999, qty: 1 }], 10)).toBe(899));
it("handles an empty cart", () => expect(cartTotal([])).toBe(0));
it.each([[0, 1000], [50, 500], [100, 0]])("discount %i%% → %i", (pct, expected) =>
expect(cartTotal([{ price: 1000, qty: 1 }], pct)).toBe(expected));
});
Property-based testing (fast-check, the frontend equivalent of Java's jqwik, Rust's proptest and Go's fuzzing) generates hundreds of random inputs to check invariants, such as "total is never negative" or "parse(format(x)) === x" (Vol. 1 ch. 5's universally quantified statements).
Component and integration tests with Testing Library
Testing Library (@testing-library/react, /angular, /vue, /svelte, /dom) renders components into a DOM (jsdom, happy-dom, or a real browser in Vitest browser mode) and queries it the way users perceive it: by role, label and text. If your test can't find the button by its role and name, neither can a screen-reader user (chapter 20).
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import { server } from "../test/msw-server";
import { CheckoutPage } from "./CheckoutPage";
import { renderWithProviders } from "../test/render"; // wraps QueryClientProvider, router, theme
it("applies a coupon and shows the discounted total", async () => {
const user = userEvent.setup();
server.use(
http.post("/api/coupons/validate", async ({ request }) => {
const { code } = (await request.json()) as { code: string };
return code === "DIWALI10" ? HttpResponse.json({ pct: 10 }) : HttpResponse.json({ error: "Invalid" }, { status: 422 });
}),
);
renderWithProviders(<CheckoutPage />);
expect(await screen.findByRole("heading", { name: /checkout/i })).toBeInTheDocument(); // findBy* waits
await user.type(screen.getByLabelText(/coupon code/i), "DIWALI10");
await user.click(screen.getByRole("button", { name: /apply/i }));
const summary = screen.getByRole("region", { name: /order summary/i });
expect(await within(summary).findByText("₹899")).toBeVisible();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("shows an error for an invalid coupon", async () => {
const user = userEvent.setup();
renderWithProviders(<CheckoutPage />);
await user.type(screen.getByLabelText(/coupon code/i), "NOPE");
await user.click(screen.getByRole("button", { name: /apply/i }));
expect(await screen.findByRole("alert")).toHaveTextContent(/invalid/i);
});
Query priority (Testing Library's guidance): getByRole (with name) > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByAltText/getByTitle > getByTestId (last resort). Variants: getBy throws if missing, queryBy returns null (for asserting absence), and findBy returns a promise that waits (for async UI). Use user-event (realistic sequences: focus, keydown, input, keyup, click) instead of fireEvent.
Test the states users see: loading skeletons, empty results, error messages with a retry, disabled buttons while submitting, validation messages, and very long or unusual content (names with emoji, RTL text).
Unit test runners: Vitest and Jest
| Vitest | Jest | |
|---|---|---|
| Engine | Vite (ESM-native, uses your Vite config and plugins) | Own transform pipeline (Babel/SWC), CommonJS heritage |
| Speed | Fast startup, smart watch mode | Mature, slower ESM story |
| API | Jest-compatible (describe, it, expect, vi.fn, vi.mock) |
jest.fn, jest.mock |
| Browser mode | Runs tests in a real browser via Playwright or WebdriverIO | jsdom only |
| Ecosystem | The default in Vite, Nuxt, SvelteKit, Astro and Angular (21+) projects | Huge legacy base, React Native |
jsdom and happy-dom simulate the DOM in Node. They're fast, but have no layout (getBoundingClientRect returns zeros), incomplete APIs (IntersectionObserver, <dialog>, CSS), and no real event dispatch from rendering. For components that depend on layout, focus behaviour or real CSS, use Vitest browser mode or Playwright component tests, which run in actual Chromium, Firefox or WebKit.
End-to-end tests with Playwright
Playwright (Microsoft) drives real Chromium, Firefox and WebKit through their automation protocols. It's fast and reliable thanks to auto-waiting and web-first assertions, and has excellent tooling:
// tests/checkout.spec.ts
import { test, expect } from "@playwright/test";
test.describe("checkout", () => {
test.use({ storageState: "playwright/.auth/user.json" }); // reuse a logged-in session (set up once)
test("buys an item with UPI", async ({ page }) => {
await page.goto("/shop/socks");
await page.getByRole("button", { name: "Add to cart" }).first().click();
await expect(page.getByRole("link", { name: /cart \(1\)/i })).toBeVisible(); // auto-retries until true
await page.getByRole("link", { name: /cart/i }).click();
await page.getByRole("button", { name: "Checkout" }).click();
await page.getByLabel("UPI ID").fill("asha@okbank");
await page.getByRole("button", { name: "Pay ₹" }).click();
await expect(page.getByRole("heading", { name: "Order confirmed" })).toBeVisible({ timeout: 15_000 });
await expect(page).toHaveURL(/\/orders\/o_\w+/);
});
});
Key Playwright concepts:
- Locators (
getByRole,getByLabel,getByText,getByTestId) are lazy and retrying: they re-resolve every time they're used, so re-renders don't break them. - Auto-waiting: actions wait for an element to be attached, visible, stable, enabled and receiving events. Web-first assertions (
expect(locator).toBeVisible(),toHaveText,toHaveURL) retry until a timeout. This removes most flakiness. Never use fixedwaitForTimeout(2000)sleeps. - Isolation: each test gets a fresh browser context (like an incognito profile) in milliseconds. Run tests in parallel across workers and shards.
- Projects run the same tests across browsers and devices (
devices["iPhone 15"], Pixel, Desktop Safari). - Auth setup: log in once in a setup project, save
storageState(cookies and storage), and reuse it in every test. - Tooling:
codegen(records interactions into code), UI mode (time-travel debugging), the Trace Viewer (below), the VS Code extension, HTML reports, and screenshots and videos on failure. - API testing (
requestfixture) seeds data through your backend API instead of the UI. It's faster and more reliable.
Playwright also has bindings for Java (com.microsoft.playwright), Python and .NET, so a Spring team can write E2E tests in Java with JUnit.
Cypress is the other major E2E tool. It runs inside the browser alongside your app, with an excellent interactive runner and time-travel snapshots. It historically had limitations with multiple tabs, cross-origin navigation and WebKit, and parallelisation is a paid feature. Both tools are solid. Playwright has become the more common default for new projects.
What to E2E-test: a few critical user journeys, such as sign-up and login, search → product → checkout → payment, and the core create/edit/delete flows, plus smoke tests after each deploy. Don't re-test every edge case end to end: that's what component and integration tests are for. E2E suites that grow to thousands of slow, flaky tests become a drag on delivery.
Test techniques
Fixtures
Fixtures provide the setup a test needs (data, pages, authenticated users, services) in a reusable, composable way, with automatic cleanup. They're like JUnit 5 extensions and @BeforeEach, or pytest fixtures:
// tests/fixtures.ts — Playwright custom fixtures
import { test as base, expect } from "@playwright/test";
type Fixtures = { seededOrder: { id: string }; cartPage: CartPage };
export const test = base.extend<Fixtures>({
seededOrder: async ({ request }, use) => {
const res = await request.post("/api/test/orders", { data: { sku: "SOCK-42", qty: 2 } }); // seed via API
const order = await res.json();
await use(order); // the test runs here
await request.delete(`/api/test/orders/${order.id}`); // teardown
},
cartPage: async ({ page }, use) => { await use(new CartPage(page)); }, // page object
});
export { expect };
// test("shows the seeded order", async ({ page, seededOrder }) => { … });
Test data principles: each test creates the data it needs (no dependence on order or shared mutable state), uses factories with sensible defaults (buildOrder({ status: "shipped" }), fishery, @faker-js/faker with a fixed seed for reproducibility), and cleans up or uses disposable environments (ephemeral databases with Testcontainers, Vol. 3).
Page Object Model: wrap page interactions (CartPage.addCoupon(code)) so tests read as user intent and selectors live in one place. Keep page objects thin. Too much abstraction hides what a test actually does (chapter 21).
Mocking
Mock at the boundaries, not in the middle. Over-mocking (mocking your own modules, hooks and child components) produces tests that pass while the real integration is broken.
| Mock | When |
|---|---|
| The network (MSW) | Almost always, for component and integration tests: realistic, and independent of the implementation |
Time (vi.useFakeTimers(), page.clock) |
Debounces, timeouts, countdowns, dates ("today" in date pickers) |
| Browser APIs missing in jsdom | IntersectionObserver, matchMedia, ResizeObserver (or use a browser test runner) |
| Randomness | crypto.randomUUID, Math.random with fixed values |
| Third-party SDKs | Payments, analytics, maps: a fake implementation behind your own interface (dependency inversion, chapter 21) |
| ❌ Your own child components, hooks, stores | Usually a smell. Test them together |
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-10-24T09:00:00+05:30"));
// … trigger a debounced search
await vi.advanceTimersByTimeAsync(300);
vi.useRealTimers();
Network interception and MSW
Mock Service Worker (MSW) intercepts requests at the network level: through a service worker in the browser, and through interceptors in Node. Your app code makes real fetch calls, unchanged, and MSW returns the mocked responses. The same handlers work in unit tests, Storybook, local development (build the frontend before the backend exists) and demos:
// src/mocks/handlers.ts
import { http, HttpResponse, delay } from "msw";
export const handlers = [
http.get("/api/orders", async ({ request }) => {
const status = new URL(request.url).searchParams.get("status");
await delay(150); // realistic latency
return HttpResponse.json({ items: fakeOrders.filter(o => !status || o.status === status), nextCursor: null });
}),
http.post("/api/orders/:id/cancel", ({ params }) =>
params.id === "o_locked"
? HttpResponse.json({ type: "about:blank", title: "Conflict", status: 409, detail: "Order already shipped" }, { status: 409 })
: new HttpResponse(null, { status: 204 })),
];
In Playwright, page.route() intercepts at the browser level. You can mock responses, modify real ones, block third-party scripts, or simulate failures and slowness:
await page.route("**/api/recommendations", (route) => route.fulfill({ status: 500 })); // test graceful degradation
await page.route("**/*.{png,jpg,webp}", (route) => route.abort()); // speed up tests
await page.route("**/api/orders", async (route) => {
const res = await route.fetch(); // call the real backend…
const json = await res.json();
await route.fulfill({ response: res, json: { ...json, items: json.items.slice(0, 1) } }); // …then edit the response
});
Also test the unhappy paths: 500s, 401s mid-session (expired token, then redirect to login), 409 conflicts, timeouts (a delayed response plus your AbortSignal.timeout), offline (context.setOffline(true)), and slow 3G (CDP network throttling).
Browser traces and debugging failures
When an E2E test fails in CI, you need to know why without reproducing it locally. Playwright's Trace Viewer records, per action: DOM snapshots before and after, screenshots, console logs, network requests, source locations and timings. You can open the trace file locally or at trace.playwright.dev.
// playwright.config.ts
export default defineConfig({
retries: process.env.CI ? 2 : 0,
use: {
trace: "on-first-retry", // record a trace when a test is retried
screenshot: "only-on-failure",
video: "retain-on-failure",
},
reporter: [["html"], ["junit", { outputFile: "results.xml" }]],
});
Flaky tests (tests that sometimes pass and sometimes fail) destroy trust in a suite. Common causes: fixed sleeps instead of waiting for state, shared test data, order dependence, animations (disable them in tests with reducedMotion: "reduce"), real time and time zones, third-party scripts, and races in the app itself, which are real bugs. Track flaky-test rates and fix or quarantine flaky tests quickly. Retries hide flakiness rather than fix it.
Specialised testing
Visual regression
Visual regression testing screenshots components or pages and compares them pixel by pixel (or perceptually) against approved baselines. It catches CSS breakage that functional tests can't: a misaligned button, a z-index regression, a theme token change that broke contrast, a font that failed to load.
await expect(page).toHaveScreenshot("checkout.png", { maxDiffPixelRatio: 0.01, animations: "disabled", mask: [page.getByTestId("timestamp")] });
Make it reliable: run in consistent containers (fonts and anti-aliasing differ between operating systems, so use Playwright's Docker images), disable animations, mask dynamic regions (dates, avatars, ads), and use fixed data. Chromatic (Storybook's service) and Percy snapshot every story across browsers, with a review UI for approving changes. Visual tests work best at the component/story level, where they're stable and diffs are easy to understand.
Accessibility testing
Automate what can be automated (chapter 20: about a third of issues), and do the rest by hand:
import AxeBuilder from "@axe-core/playwright";
test("checkout has no detectable a11y violations", async ({ page }) => {
await page.goto("/checkout");
const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag22aa"]).analyze();
expect(results.violations).toEqual([]);
});
test("checkout is keyboard operable", async ({ page }) => {
await page.goto("/checkout");
await page.keyboard.press("Tab"); // skip link first
await expect(page.getByRole("link", { name: "Skip to main content" })).toBeFocused();
// … Tab through the form, submit with Enter, confirm focus moves to the error summary on invalid input
});
Use role-based queries throughout your tests (which tests the accessibility tree for free), axe checks in component tests (vitest-axe) and in Storybook's a11y addon, plus eslint-plugin-jsx-a11y. Schedule periodic manual screen-reader passes on the critical journeys.
Performance testing
Prevent performance regressions in CI (chapter 27 covers the metrics):
- Lighthouse CI: run Lighthouse on key pages per PR, with budgets (
performance >= 0.9,largest-contentful-paint <= 2500, total JS ≤ 200 KB). Run several times and take the median, because lab results are noisy. - Bundle-size checks: size-limit, bundlesize, Angular budgets and
@next/bundle-analyzerfail the PR if a change adds 80 KB. - Interaction performance: Playwright with CDP to record traces and long tasks, or measure INP-like interaction latency with the
web-vitalslibrary inside tests. - Load testing the backend behind the frontend (k6, Gatling; Vol. 3).
- Field data (RUM) is the ground truth. Lab tests catch regressions, and RUM tells you what users actually experience (chapter 32).
Contract testing
Frontend and backend teams often break each other with API changes: a renamed field, a newly nullable value, a changed enum. Contract testing checks compatibility without spinning up both systems together:
- Consumer-driven contracts (Pact): the frontend's tests record the interactions it expects (request → minimal response shape) into a contract file. The backend's CI verifies that its real implementation satisfies every consumer's contract (Pact JVM for Spring, pact-go, pact-rust), and the Pact Broker tracks which versions are compatible ("can I deploy?").
- Schema-based contracts: an OpenAPI spec is the contract. The backend validates its responses against it in tests (or generates it from code: springdoc), and the frontend generates its types and client from it (openapi-typescript, orval) and validates MSW mocks against it (so mocks can't drift from reality). Tools: Schemathesis and Dredd fuzz an implementation against its spec.
- Runtime validation with Zod or Valibot at the boundary (chapter 16) catches what slips through, in production, with telemetry.
// Pact consumer test (frontend)
await provider
.given("order o_42 exists")
.uponReceiving("a request for order o_42")
.withRequest({ method: "GET", path: "/api/orders/o_42" })
.willRespondWith({ status: 200, body: { id: like("o_42"), total: integer(899), status: regex(/pending|shipped/, "shipped") } })
.executeTest(async (mock) => {
const order = await new OrdersApi(mock.url).get("o_42");
expect(order.status).toBe("shipped");
});
Frontend testing compared with backend testing
| Concept | Frontend | Java / Spring (Vol. 3) | Go | Rust |
|---|---|---|---|---|
| Unit runner | Vitest / Jest | JUnit 5 | go test |
cargo test |
| Mocks | vi.fn, MSW |
Mockito, WireMock | interfaces + fakes, httptest | mockall, wiremock-rs |
| Component/slice tests | Testing Library | @WebMvcTest, @DataJpaTest |
httptest.NewRecorder |
axum oneshot |
| Real dependencies | Playwright against staging | Testcontainers | testcontainers-go | testcontainers-rs |
| E2E browser | Playwright (TS) | Playwright Java, Selenium | chromedp | fantoccini |
| Contracts | Pact JS, OpenAPI | Pact JVM, Spring Cloud Contract | pact-go | pact-rust |
| Property-based | fast-check | jqwik | testing/quick, fuzzing |
proptest |
Lab: testing the tests
Run on a small React project with Vitest 5.0, Testing Library, MSW 2, jsdom and Playwright 1.63 (Chromium). These experiments measure the things that decide whether a test suite is worth having: its speed, whether its tests would actually catch bugs, and whether they pass for the right reasons.
Experiment 1: what each level costs
The project's suite: 9 unit tests for the cart reducer, 2 component tests for the shopping list, 2 component tests for the menu page with MSW, and 1 Playwright E2E test.
unit (9 tests, cart.test.js) 233 ms for the file, 0–3 ms per test
component (4 tests, jsdom + Testing Library) about 1 s environment start-up per file, then 33–460 ms per test
end-to-end (1 test, Playwright + Chromium) 3.2 s total: build and start the server, launch the browser, 884 ms test
Per test, a unit test is roughly a thousand times cheaper than an E2E test. That's not a reason to avoid E2E tests; it's a reason to give each behaviour one test at the cheapest level that can catch its bugs: the coupon arithmetic in a unit test, "the error message appears and Retry works" in a component test with a mocked API, "the real app builds and a shopper can complete a purchase" in E2E. Vitest also reported the jsdom environment as 61% of the component tests' time, which is why it runs files in parallel workers, and why many teams now run component tests in a real browser instead (Vitest browser mode, Playwright component testing) when jsdom's simulated layout isn't enough.
Experiment 2: would the tests catch a bug? (mutation testing)
Code coverage tells you which lines ran during tests, not whether any test would notice if they were wrong. Mutation testing answers that directly: make small deliberate changes ("mutants") to the code, run the tests, and see if they fail. A 30-line script did it for the cart reducer:
const mutants = [
["qty + 1 → qty + 2", "qty: l.qty + 1", "qty: l.qty + 2"],
["new dish qty 1 → 0", "{ ...action.dish, qty: 1 }", "{ ...action.dish, qty: 0 }"],
["remove keeps instead of drops", "l.id !== action.id", "l.id === action.id"],
["discount 0.9 → 0.95", "0.9 : 1", "0.95 : 1"],
["coupon check inverted", 's.coupon === "CHAI10"', 's.coupon !== "CHAI10"'],
["Math.round → Math.floor", "Math.round(", "Math.floor("],
["price × qty → price + qty", "l.price * l.qty", "l.price + l.qty"],
];
// for each: apply it, run `vitest run src/cart.test.js`, record whether the suite failed
killed qty + 1 → qty + 2
killed new dish qty 1 → 0
SURVIVED remove keeps instead of drops
killed discount 0.9 → 0.95
killed coupon check inverted
SURVIVED Math.round → Math.floor
killed price × qty → price + qty
mutation score: 5/7
For comparison, the coverage report for the same tests (vitest run --coverage):
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
cart.js | 78.57 | 80 | 83.33 | 80 | 11,13
Coverage did point at one gap (line 11, the removed case, never ran). But the rounding mutant survived on a line that was covered: every expected total happened to be a whole number, so rounding up or down made no difference, and no amount of coverage could reveal that the assertions were too weak. Adding two tests, one that removes a dish and one with a 55-rupee vada and the coupon (49.5, which must round to 50), killed both:
killed remove keeps instead of drops
killed Math.round → Math.floor
mutation score: 7/7
Tests 13 passed (13)
Tools such as Stryker (JavaScript/TypeScript), PIT (Java) and cargo-mutants (Rust) generate hundreds of mutants automatically. They're slow, so teams run them nightly or on critical modules (pricing, permissions) rather than on every commit.
Experiment 3: flaky tests and fixed waits
A page loads its menu from an API that takes a random 50–450 ms (as real APIs do). The same check, written three ways, ran 40 times each:
await page.waitForTimeout(200); ok = (await page.locator("li").count()) === 1; // fixed wait, then read
await page.waitForTimeout(1000); ok = (await page.locator("li").count()) === 1; // longer fixed wait
await expect(page.locator("li")).toHaveText(["Masala dosa"]); // auto-waiting assertion
fixed wait 200 ms, then read failed 22/40 runs | average time 231 ms
fixed wait 1000 ms, then read failed 0/40 runs | average time 1031 ms
auto-waiting assertion failed 0/40 runs | average time 427 ms
The 200 ms version is a flaky test: it fails about half the time with no code change, so people learn to ignore red builds, which defeats the purpose of having tests. The 1-second version "fixes" it by making every run slow, and it will fail again the day the API is slower on a busy CI machine. The auto-waiting assertion polls until the condition holds (up to a timeout), so it's both reliable and as fast as the app allows. The same rule applies in component tests: use findBy… and waitFor, never setTimeout. When a test does flake, Playwright's trace (trace: "retain-on-failure") records every action, network request, console message and DOM snapshot, so you can step through the failing run in the trace viewer instead of guessing.
Try it yourself
- Delete the
afterEach(() => server.resetHandlers())line from the MSW test file and run the two menu tests in reverse order. What happens, and why? - Install Stryker (
npm init stryker) on a module you own. What's its mutation score, and which surviving mutant surprises you most? - Make experiment 3's API occasionally return 500. Write the E2E test so it verifies the error message and the Retry button, using Playwright's
page.route()to force the failure deterministically. - Run your project's E2E suite with
--repeat-each=20and count flaky tests.
Revision sheet: frontend testing
Key ideas
- Tests buy the confidence to change code; test behaviour through public interfaces, not implementation details.
- Levels: unit (pure logic), component/integration (rendered UI with mocked boundaries), E2E (real app, real browser); one test per behaviour at the cheapest level that can catch its bugs; the "trophy" weights integration tests.
- Testing Library queries by role, label and text (
getBy,queryBy,findBy); user-event for realistic interaction; jest-dom matchers. - Test doubles: stubs, mocks, fakes, spies; mock at boundaries (network with MSW, time with fake timers), not internal modules.
- E2E with Playwright: locators by role, auto-waiting assertions, fixtures,
page.route()for network control, traces, parallel workers, multiple browsers. - Reliability: no fixed sleeps; isolate tests (reset handlers, storage, databases); deterministic data and clocks; retries only as a last resort and tracked.
- Quality of the suite: coverage shows what ran; mutation score shows what would be caught.
- Specialised: visual regression (screenshot diffs), accessibility (axe in component and E2E tests), performance budgets (Lighthouse CI), contract tests against API schemas (OpenAPI, Pact).
Numbers to remember
- Lab: unit tests about 1 ms each; component tests tens to hundreds of ms plus about 1 s jsdom start-up per file; an E2E run about 3 s.
- Lab: a 200 ms fixed wait failed 22/40 runs; auto-waiting failed 0/40.
- Lab: 80% line coverage; 2 of 7 mutants survived, one of them on a fully covered line.
Pitfalls
- Testing implementation details (state values, class names, internal calls); snapshot tests of entire components that everyone updates blindly.
getByfor async content; fixedsetTimeout/waitForTimeoutwaits; shared state between tests.- Over-mocking (mocking the module under test's collaborators until nothing real is tested).
- Too many E2E tests for logic that unit tests could cover; no E2E test for the money path.
- Ignoring flaky tests instead of fixing or quarantining them.
- Chasing a coverage percentage rather than meaningful assertions.
Glossary
- Assertion: a check that fails the test when false.
- Test double: any stand-in for a real dependency (stub, mock, fake, spy).
- Flaky test: a test that passes and fails without code changes.
- Auto-waiting: retrying an action or assertion until the page is ready or a timeout passes.
- Mutant: a deliberately altered version of the code used to check that tests catch changes.
- Trace: a recorded timeline of a test run (actions, network, DOM snapshots) for debugging.