I built Per Diem, a mobile-first menu for a multi-location café, on my own in a day. It reads the Square catalogue through a small backend. You pick a location, then browse the menu by category or search it. The front end is React 19, TypeScript and TanStack Query, and it has 63 tests: 31 unit, 15 integration and 17 end-to-end, two of which are automated accessibility audits.
The levels answer different questions. A unit test checks one component or function on its own: does the search box wait 300 ms before firing? An integration test renders several real pieces together against a faked network: does the menu list fetch, group and filter? An end-to-end (E2E) test drives a real browser against the real backend: can someone pick a location and see a menu? The accessibility audit asks whether the rendered page breaks rules a machine can detect. Each level catches failures the others cannot see.
How the three test levels are laid out
The folders match the levels: src/__tests__/unit, integration, e2e, and mocks for the shared fake API. Vitest runs the first two in jsdom, a browser-like DOM implemented in Node. Playwright runs the third in a real browser. The Vitest config keeps the two runners apart:
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./src/__tests__/setup.ts"],
include: ["src/__tests__/**/*.test.{ts,tsx}"],
exclude: ["src/__tests__/e2e/**"],
},
npm test runs the 46 Vitest tests with no backend and no network. npm run test:e2e runs the 17 Playwright tests, and it needs both servers.
What unit tests cover: one component, one behaviour
The unit level has four files: price formatting (8 tests), SearchBar (10), MenuItemCard (8) and LocationSelector (5). The price tests are the plainest. Square sends money as cents, and formatMoney({ amount: 1250, currency: "USD" }) must return "$12.50".
The search bar is where unit tests pay for themselves. It debounces, meaning it waits until typing pauses before reporting the query. Timing is awkward to test through a browser and easy with fake timers:
it("debounces rapid typing to only call once", () => {
render(<SearchBar onSearch={onSearch} />);
const input = screen.getByRole("searchbox");
fireEvent.change(input, { target: { value: "b" } });
vi.advanceTimersByTime(100);
fireEvent.change(input, { target: { value: "bu" } });
vi.advanceTimersByTime(100);
fireEvent.change(input, { target: { value: "bur" } });
vi.advanceTimersByTime(300);
expect(onSearch).toHaveBeenCalledOnce();
expect(onSearch).toHaveBeenCalledWith("bur");
});
Other tests in the file check that nothing fires at 200 ms, that Escape clears the input, and that the clear button only appears when there is text.
Mocking the API with MSW instead of mocking fetch
Anything that loads data needs an API. I used MSW (Mock Service Worker), which intercepts requests at the network layer. The app's own fetch wrapper and TanStack Query hooks run unmodified, and only the response is fake. The setup file starts it for every Vitest test:
// Start MSW server before all tests
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
// Reset handlers after each test to prevent interference between tests
afterEach(() => server.resetHandlers());
// Clean up after all tests
afterAll(() => server.close());
onUnhandledRequest: "error" is the important line. A request with no handler fails the test, so a new endpoint cannot slip through unmocked. The default handlers return two locations, two categories and two menu items.
A single test can override a handler to force a failure. This one checks the error state of the location picker:
server.use(
http.get("/api/locations", () => {
return HttpResponse.json({ error: "Server Error" }, { status: 500 });
})
);
// Set retryDelay to 0 so retries happen immediately (useLocations has retry: 2)
const qcNoRetry = new QueryClient({
defaultOptions: { queries: { retryDelay: 0 } },
});
The comment records something I hit while writing it. The useLocations hook sets retry: 2 itself, which overrides the retry: false my other test wrappers put on the query client. The alert only renders after the retries finish, so the test sets the retry delay to zero and waits for role="alert".
What integration tests cover: components working together
The integration level has three files. MenuFlow (6 tests) renders the location picker, or the category tabs and menu list, inside the real providers, and waits for the fixture data to appear: both locations, both categories, "Classic Burger" and its price of $12.00. That last assertion crosses the fetch wrapper, the query hook, the list, the card and the price formatter.
DarkMode (4 tests) renders the header inside the theme provider and clicks the toggle. The theme cycles system, light, dark. jsdom has no matchMedia, so the setup file stubs it to report a light system theme, and the test clicks twice to reach dark. It asserts on two side effects: the dark class on the <html> element, and the value saved to localStorage.
SearchFlow (5 tests) gives the menu list a search query and checks for the empty state on no match, the burger on "burger", and both items on an empty query.
What end-to-end tests cover with Playwright
The Playwright config starts both servers and waits for each URL to respond:
webServer: [
{
command: "npm run dev",
cwd: "../perdiem-backend",
url: "http://localhost:3001/health",
reuseExistingServer: !process.env.CI,
timeout: 30000,
},
{
command: "npm run dev",
url: "http://localhost:5173",
// ...
},
],
There are 17 tests in three files, and each runs in two projects, desktop Chromium and an emulated Pixel 5. They cover what only a real browser and a real backend can show: a selected location survives a page reload, the page has no horizontal scroll at 375 px wide, and a search for a nonsense string leaves zero items on screen.
The backend serves a live Square sandbox, so I do not control the data. The E2E tests therefore assert on structure, never on content. They find elements by ARIA role (the role an element exposes to assistive technology): listbox and option for locations, tablist and tab for categories, article for menu items. That has a side benefit. If someone removes a role from a component, the journey tests fail.
Running an automated accessibility check with axe-core
axe-core is a rules engine that inspects a rendered page for accessibility violations. Two Playwright tests inject it, one on the location screen and one on the menu screen:
const violations = await page.evaluate(async () => {
// @ts-ignore
const results = await window.axe.run(document, {
runOnly: ["wcag2a", "wcag2aa", "wcag21aa"],
});
return results.violations;
});
const criticalViolations = violations.filter(
(v: { impact: string }) => v.impact === "critical" || v.impact === "serious"
);
expect(criticalViolations.length).toBe(0);
It runs the WCAG 2 A and AA and WCAG 2.1 AA rule sets and fails on any violation rated serious or critical. An audit like this only checks what a rule can detect. So the same file has four keyboard tests: Tab and Enter on the location screen, arrow keys on the category tabs, Escape to clear the search, and Enter on the theme toggle.
Trade-offs and what I would do differently
- The search integration tests do not join the pieces.
SearchFlowtests the search bar and the menu list separately and passes the query in as a prop. The wiring between them is only covered by one E2E test. - axe-core loads from a CDN at test time. The audit needs internet access. I would install it as a dev dependency.
- E2E depends on live sandbox data and fixed waits. Several tests sleep for 400 or 500 ms. I would seed known data and wait on conditions.
Takeaways
- Unit tests are the right place for timing and edge cases, because fake timers make a 300 ms debounce exact and instant.
- Mock the network with MSW, not your own fetch function, so the real API client and query hooks run in every test.
- Make unhandled requests an error so a missing mock fails loudly.
- Query by ARIA role in end-to-end tests, and the journey tests also guard your accessibility markup.
- An axe-core audit is cheap to add to an existing Playwright run, but pair it with keyboard tests, because a rules engine only checks what a rule can detect.