Lab: Test a Checkout Flow at Every Level
Assemble the full toolkit around one feature: unit tests for a price formatter, component tests with mocked HTTP, a Playwright checkout journey, an axe gate and a stability run.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: unit test the price formatter
- Step 2: component test the search results
- Step 3: the end-to-end journey
- Step 4: make it a gate you can trust
- When a step fails
- Check your understanding
- Apply it
- Review prompt
Lessons of Component & End-to-End Testing
- What to Test in a Frontend, and at Which Level Concept · 20 min
- Component Tests That Read Like User Stories Worked example · 25 min
- Mock the Network, Not Your Code Worked example · 20 min
- End-to-End Journeys with Playwright Worked example · 25 min
- Lab: Test a Checkout Flow at Every Level Lab · 30 min
- Check: Fix the Flaky and the Brittle Knowledge check · 8 questions
What you will learn
- Write component tests with Vitest and Testing Library that query by role and label, simulate user events and assert visible behavior rather than implementation details.
- Isolate tests from real services by mocking HTTP at the network level (for example with Mock Service Worker) and cover loading, error and success states.
- Write Playwright end-to-end tests for critical user journeys with resilient locators, web-first assertions and automated axe accessibility scans.
- Choose a balanced mix of unit, component and end-to-end tests for a feature, and diagnose flaky tests using traces and retry data.
Prerequisites: React Components & State
01. Goal and setup
This lab assembles the toolkit from the previous lessons around one feature: a shop checkout. You will prove behaviour at three levels — a unit test for the price formatter, component tests for the search results, a Playwright journey across the checkout page — then gate quality with an axe scan and check the suite for flakiness by running it repeatedly.
Every file the lab needs is printed on this page, so you do not have to piece it together from earlier lessons. Everything runs locally with free, open-source tools. The install command pins the versions this lab was checked with on 26 November 2026: Node 22, React 19.3.1, Vitest 5.1.2, jsdom 31.0.1, Testing Library (react 16.3.3, dom 10.4.2, user-event 14.6.13, jest-dom 8.0.0), MSW 3.0.8, Playwright 1.64.1 with the Chromium build it downloads, and @axe-core/playwright 4.14.1. TypeScript 7.0.2 is there for your editor; Vitest and Playwright compile the test files themselves. MSW 3 imports http from msw/http and names the unhandled-request option onUnhandledFrame, as the network-mocking lesson explains. You will build this folder:
checkout-testing/
├── package.json
├── vitest.config.ts
├── playwright.config.ts
├── server.mjs static server for the E2E test
├── src/
│ ├── api.ts fetch client
│ ├── product-search.tsx component under test
│ ├── product-search.test.tsx component tests (MSW)
│ ├── format-price.test.ts unit test
│ ├── setup-tests.ts matchers, cleanup, mock server
│ └── mocks/ handlers.ts and server.ts
├── public/
│ ├── checkout.html checkout page the E2E test drives
│ └── format-price.js shared arithmetic module
└── e2e/
└── checkout.spec.ts the journey and the axe scanmkdir checkout-testing && cd checkout-testing
npm init -y && npm pkg set type=module
mkdir -p src/mocks public e2e
npm install [email protected] [email protected]
npm install -D [email protected] [email protected] @testing-library/[email protected] \
@testing-library/[email protected] @testing-library/[email protected] \
@testing-library/[email protected] [email protected] @playwright/[email protected] \
@axe-core/[email protected] [email protected]
npx playwright install chromiumWhy every level, rather than one good suite? Because each layer catches a different class of bug. A unit test fails the moment rounding changes, seconds after the edit. A component test fails when a state stops rendering or a label disconnects. The journey fails when the pieces stop working together — a script that no longer loads, an endpoint that moved, a page that renders but cannot be paid with. Removing any layer means that class of bug reaches users before a machine notices.
One config file comes first. vitest.config.ts picks jsdom as the default test environment, loads the setup file, and limits Vitest to src/. Without that include, Vitest's default pattern also matches e2e/checkout.spec.ts and would try to run the Playwright spec as a Vitest file.
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
include: ['src/**/*.test.{ts,tsx}'],
setupFiles: './src/setup-tests.ts',
},
});Next, the search client that the component calls. Two details matter. The id is a number, matching the catalogue in the mock handlers below. And the request URL is absolute. Node's own fetch has no page to resolve a bare /api/products against and throws Failed to parse URL; building the URL from location.origin works in a browser and in Vitest's jsdom environment (where it is http://localhost:3000), whether or not a mocking library patches fetch.
export interface Product {
id: number;
name: string;
price: number;
}
// An absolute URL works in the browser and in Node, where fetch has no base URL.
// In the jsdom test environment, location.origin is http://localhost:3000.
export async function searchProducts(query: string): Promise<Product[]> {
const url = new URL('/api/products', location.origin);
url.searchParams.set('q', query);
const res = await fetch(url);
if (!res.ok) throw new Error(`Search failed: ${res.status}`);
return res.json();
}02. Step 1: unit test the price formatter
Start at the bottom. The checkout page shows a total such as £98.49; the arithmetic lives in formatPrice, a pure function shared by the page script. Pure logic needs no DOM and no network, so its tests are the cheapest to write and the first to fail when someone changes rounding. The @vitest-environment node comment tells Vitest to run this one file without jsdom, which makes the point explicit. Pin the edges that matter to a shop: whole pounds, and the half-penny rounding that matches a commercial till — one hundred point five pence rounds up to £1.01.
export function formatPrice(pence) {
const rounded = Math.round(pence);
return `£${(rounded / 100).toFixed(2)}`;
}// @vitest-environment node
import { describe, expect, it } from 'vitest';
import { formatPrice } from '../public/format-price.js';
describe('formatPrice', () => {
it('formats pence as pounds with two decimal places', () => {
expect(formatPrice(9849)).toBe('£98.49');
});
it('keeps whole pounds at .00', () => {
expect(formatPrice(900)).toBe('£9.00');
});
it('rounds half pennies like a till', () => {
expect(formatPrice(100.5)).toBe('£1.01');
expect(formatPrice(345.5)).toBe('£3.46');
});
});Before you run it: vitest.config.ts loads src/setup-tests.ts for every test file, and that file (with the mock server it imports) is created in step 2. Either create the three files the setup needs now (src/mocks/handlers.ts, src/mocks/server.ts and src/setup-tests.ts from step 2), or comment out the setupFiles line for this one run and restore it afterwards.
npx vitest run src/format-price.test.ts RUN v5.1.2
✓ src/format-price.test.ts (3 tests)
Test Files 1 passed (1)
Tests 3 passed (3)03. Step 2: component test the search results
The middle layer is the component suite from the component lesson and the network-mocking lesson, collected here in full. The component waits for typing to settle, then asks the network:
import { useEffect, useState } from 'react';
import { searchProducts, type Product } from './api';
type State =
| { status: 'loading' }
| { status: 'error' }
| { status: 'success'; products: Product[] };
export function ProductSearch() {
const [query, setQuery] = useState('');
const [state, setState] = useState<State>({ status: 'loading' });
useEffect(() => {
let active = true;
const timer = setTimeout(() => {
setState({ status: 'loading' });
searchProducts(query)
.then((products) => {
if (active) setState({ status: 'success', products });
})
.catch(() => {
if (active) setState({ status: 'error' });
});
}, 150);
return () => {
active = false;
clearTimeout(timer);
};
}, [query]);
return (
<section aria-labelledby="search-heading">
<h2 id="search-heading">Product search</h2>
<label htmlFor="search-input">Search products</label>
<input id="search-input" type="search" value={query}
onChange={(event) => setQuery(event.target.value)} />
{state.status === 'loading' && <p role="status">Loading…</p>}
{state.status === 'error' &&
<p role="alert">Something went wrong. Please try again.</p>}
{state.status === 'success' && state.products.length === 0 &&
<p>No products match “{query}”.</p>}
{state.status === 'success' && state.products.length > 0 && (
<ul>
{state.products.map((product) => (
<li key={product.id}>{product.name} — £{product.price.toFixed(2)}</li>
))}
</ul>
)}
</section>
);
}MSW answers that request at the network boundary. The handler is the default answer for every test; server.listen with onUnhandledFrame: 'error' fails any test that calls an endpoint no handler covers, and resetHandlers removes per-test overrides so they cannot leak.
import { http, HttpResponse } from 'msw/http';
import type { Product } from '../api';
const catalogue: Product[] = [
{ id: 1, name: 'Trail shoes', price: 89.5 },
{ id: 2, name: 'Running shoes', price: 74 },
];
export const handlers = [
http.get('*/api/products', ({ request }) => {
const query = new URL(request.url).searchParams.get('q') ?? '';
return HttpResponse.json(
catalogue.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase()),
),
);
}),
];import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterAll, afterEach, beforeAll } from 'vitest';
import { server } from './mocks/server';
beforeAll(() => server.listen({ onUnhandledFrame: 'error' }));
afterEach(() => {
cleanup();
server.resetHandlers();
});
afterAll(() => server.close());The three tests cover the loading note and the list that replaces it, the empty message, and the error alert forced by a server.use() override for one test:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw/http';
import { describe, expect, it } from 'vitest';
import { server } from './mocks/server';
import { ProductSearch } from './product-search';
describe('ProductSearch', () => {
it('shows a loading note, then the matching products', async () => {
const user = userEvent.setup();
render(<ProductSearch />);
expect(screen.getByRole('status')).toHaveTextContent(/loading/i);
await user.type(
screen.getByRole('searchbox', { name: 'Search products' }),
'shoes',
);
const list = await screen.findByRole('list');
expect(list).toHaveTextContent('Trail shoes');
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});
it('says so when nothing matches the query', async () => {
const user = userEvent.setup();
render(<ProductSearch />);
await user.type(
screen.getByRole('searchbox', { name: 'Search products' }),
'kettlebells',
);
expect(
await screen.findByText('No products match “kettlebells”.'),
).toBeInTheDocument();
expect(screen.queryByRole('list')).not.toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
it('shows an error message when the request fails', async () => {
server.use(
http.get('*/api/products',
() => new HttpResponse(null, { status: 500 })),
);
render(<ProductSearch />);
expect(await screen.findByRole('alert')).toHaveTextContent(/went wrong/i);
expect(screen.queryByRole('list')).not.toBeInTheDocument();
});
});npx vitest run ✓ src/format-price.test.ts (3 tests)
✓ src/product-search.test.tsx (3 tests)
Test Files 2 passed (2)
Tests 6 passed (6)Six tests across two files, finished in seconds, with no backend anywhere. This is the suite that runs on every save while you develop. If one of its tests fails, you are usually a few lines from the cause — that short feedback loop is the reward for keeping the levels separate. The same suite runs unchanged in CI; only the journey below needs a browser to run in.
04. Step 3: the end-to-end journey
The top layer drives the real page. The checkout page is plain HTML plus a module script that shows the total and handles the pay action; in a real project this is your production build served by a preview server. Provide the page and a small static server:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Checkout</title>
<script type="module">
import { formatPrice } from './format-price.js';
document.getElementById('total').textContent = formatPrice(9849);
const form = document.querySelector('form');
const payBtn = document.getElementById('pay-btn');
const status = document.getElementById('status');
form.addEventListener('submit', (e) => {
e.preventDefault();
payBtn.disabled = true;
status.textContent = 'Processing payment…';
setTimeout(() => {
status.textContent = 'Order confirmed. Thank you!';
}, 50);
});
</script>
</head>
<body>
<main>
<h1>Checkout</h1>
<p>Order total: <span id="total"></span></p>
<form>
<label for="card">Card number</label>
<input id="card" type="text" autocomplete="cc-number" required>
<button id="pay-btn" type="submit">Pay now</button>
</form>
<div id="status" role="status" aria-live="polite"></div>
</main>
</body>
</html>import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
const root = path.resolve('public');
const mimeTypes = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
};
const server = http.createServer((req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
const urlPath = pathname === '/' ? '/checkout.html' : pathname;
const filePath = path.join(root, path.normalize(urlPath));
const inside = filePath.startsWith(root + path.sep);
if (inside && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
const type = mimeTypes[path.extname(filePath)] || 'text/plain';
res.writeHead(200, { 'Content-Type': type });
fs.createReadStream(filePath).pipe(res);
} else {
res.writeHead(404);
res.end('Not found');
}
});
// Must match webServer.port and use.baseURL in playwright.config.ts.
const port = Number(process.env.PORT) || 4173;
server.listen(port, '127.0.0.1', () => {
console.log(`Server running at http://localhost:${port}`);
});Playwright starts and stops the server itself through webServer, and waits until something answers on the configured port before running any test. That is why the port must be the same in three places — server.mjs, webServer.port and use.baseURL. If the server listened on another port, Playwright would wait for the webServer timeout and fail before a single test ran. The env entry makes the agreement explicit.
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
use: {
baseURL: 'http://localhost:4173',
trace: 'retain-on-failure',
},
webServer: {
command: 'node server.mjs',
port: 4173,
env: { PORT: '4173' },
reuseExistingServer: false,
},
});The spec follows the pattern from the journeys lesson, written for this page: its heading is Checkout, its button is Pay now, and its status ends at Order confirmed. Thank you!. Copying a spec written for a different page is a classic way to get a suite that can never pass.
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('paying for an order shows the confirmation', async ({ page }) => {
await page.goto('/');
await expect(page.getByRole('heading', { name: 'Checkout' })).toBeVisible();
await expect(page.getByText('Order total: £98.49')).toBeVisible();
await page.getByLabel('Card number').fill('4242 4242 4242 4242');
const pay = page.getByRole('button', { name: 'Pay now' });
await pay.click();
await expect(page.getByRole('status')).toHaveText(
'Order confirmed. Thank you!',
);
await expect(pay).toBeDisabled();
});
test('checkout page has no accessibility violations', async ({ page }) => {
await page.goto('/');
await expect(page.getByText('Order total: £98.49')).toBeVisible();
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'])
.analyze();
expect(results.violations).toEqual([]);
});npx playwright testRunning 2 tests using 1 worker
✓ 1 e2e/checkout.spec.ts:4:1 ›
paying for an order shows the confirmation (2.1s)
✓ 2 e2e/checkout.spec.ts:20:1 ›
checkout page has no accessibility violations (822ms)
2 passed (5.1s)The journey test opens the page, reads the total, fills the card number, pays and asserts the confirmation and the disabled button — all with role, label and text locators and web-first assertions that retry until they pass or time out. The second test is the axe scan with the WCAG 2.x tags, which fails the run on any violation axe can detect automatically.
Prove that the gate can fail before you trust it. Replace <label for="card">Card number</label> with <span>Card number</span>, run npx playwright test -g accessibility, read the failure, then put the label back. Both tests depend on the label — the journey finds the input through it — which is exactly why it is worth guarding.
Running 1 test using 1 worker
…
Error: expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 97
- Array []
+ Array [
+ Object {
+ "description": "Ensure every form element has a label",
+ "help": "Form elements must have labels",
…
+ "id": "label",
…
1 failedIt is worth naming what the journey proved that the lower levels could not. The page script really loaded as a browser module; the role="status" element really showed the confirmation; the button really became unclickable. A component test asserts those states from the inside; the journey verifies them from where a shopper sits.
05. Step 4: make it a gate you can trust
A test that passes once is a promise; passing five consecutive repeat cycles (10 runs across the two tests) without flaking is strong evidence. Playwright repeats each test in one invocation with --repeat-each=5. Run the suite with single-worker execution so runs cannot interfere:
npx playwright test --repeat-each=5 --workers=1Running 10 tests using 1 worker
✓ 1 e2e/checkout.spec.ts:4:1 ›
paying for an order shows the confirmation (2.0s)
✓ 2 e2e/checkout.spec.ts:20:1 ›
checkout page has no accessibility violations (801ms)
✓ 3 e2e/checkout.spec.ts:4:1 ›
paying for an order shows the confirmation (2.8s)
✓ 4 e2e/checkout.spec.ts:20:1 ›
checkout page has no accessibility violations (793ms)
✓ 5 e2e/checkout.spec.ts:4:1 ›
paying for an order shows the confirmation (2.0s)
✓ 6 e2e/checkout.spec.ts:20:1 ›
checkout page has no accessibility violations (769ms)
✓ 7 e2e/checkout.spec.ts:4:1 ›
paying for an order shows the confirmation (2.2s)
✓ 8 e2e/checkout.spec.ts:20:1 ›
checkout page has no accessibility violations (814ms)
✓ 9 e2e/checkout.spec.ts:4:1 ›
paying for an order shows the confirmation (2.2s)
✓ 10 e2e/checkout.spec.ts:20:1 ›
checkout page has no accessibility violations (782ms)
10 passed (24.3s)A green repeated run is evidence the journey does not depend on timing. It says nothing about parallel workers fighting over shared data — that is what CI is for, running the whole suite with real workers against an isolated environment, which is the final home for everything you built here.
When the suite moves into CI, keep the order you built in: unit and component tests first, because they fail in seconds and need no browser; the journey and the axe scan after, on the machines that have one. A red journey then means the pieces broke, and a red scan means the page lost its way — two different failures, two different readers.
06. When a step fails
07. Check your understanding
08. Apply it
Extend the lab in the direction of the practice task for this skill: add a Playwright project that runs the journey in WebKit and in a mobile viewport, and make one journey cover an expired session that ends at the sign-in page. Then run the whole suite ten times in a row and treat the first red as a diagnosis exercise, not a nuisance — open the trace before you change anything.
09. Review prompt
Without looking back: list the three levels in the order you built them and what each proved. Name the four visible states of the search component and the tool that faked the network outcomes. Say which three settings must agree on the port, what the axe gate covers and which tags it used, and what --repeat-each does and does not prove.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.