Volume 2 Exercises: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Exercises: The Web Frontend

V2·26

Frontend Testing

Exercises for Volume 2, chapter 26: what to test and why; unit tests; component and integration tests with Testing Library; Vitest and Jest; end-to-end tests with Playwright; fixtures, mocking, network interception with MSW, and browser traces; visual regression, accessibility, performance and contract testing; and how frontend testing compares with backend testing. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~14 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. The measured exercises use Vitest 3.2.7 with jsdom, Testing Library (React 16.3.3, user-event), MSW 2.15, Zod, React 19.3.1, Playwright with Chromium 153, and pixelmatch 8, the image comparator Playwright's screenshots use by default. Every quoted output is real. Four of them surprise people:

  • P1: a test using a CSS-class selector broke when the class was renamed, but kept passing when the button became an inaccessible <div>.
  • P3: an out-of-date mock let a test pass while the page showed "₹NaN".
  • P4: Vitest's fake timers made a Testing Library test hang until a one-line shim was added.
  • P5: pixelmatch at threshold 0.1 reported 0 differing pixels when a brand colour changed from #8a4b08 to #9a5b18.

The chapter's lab measured the cost of each test level (unit 0–3 ms per test, component 33–460 ms plus about 1 s of start-up, E2E 3.2 s), mutation testing (score 5/7, then 7/7 after two better tests), and flaky fixed waits (22 of 40 runs failed at 200 ms; 0 of 40 with an auto-waiting assertion). The exercises build on those.

Coverage map.

Chapter component Exercises
what to test and why; the levels and their costs T1, C2
unit tests T2, P2
component and integration tests with Testing Library; queries T3, P1
Vitest and Jest; fake timers T4, P4
end-to-end tests with Playwright T5, P6
fixtures T6, P6
mocking T6, P3
network interception and MSW T6, P3
browser traces and debugging failures T5, P6
visual regression T7, P5
accessibility testing T8
performance testing T8, P7
contract testing T9, P8
frontend vs backend testing T9

Theory

T1. What to test, and at which level

  1. The lab measured: unit tests 0–3 ms each, component tests 33–460 ms each plus about 1 s of environment start-up per file, and an E2E test 3.2 s including build and browser. Using the rule "one test per behaviour at the cheapest level that can catch its bugs", place these TiffinBox behaviours: GST rounding, the coupon rules, "the error message appears and Retry works", keyboard navigation of the category tabs, "a shopper can order lunch", and the menu looking right on a 320 px phone.
  2. Compare the test pyramid, the testing trophy (static analysis at the base, integration in the middle) and the honeycomb. What does each emphasise, and why is "write tests, not too many, mostly integration" common advice for frontends?
  3. What should you not test (implementation details, third-party libraries, framework behaviour, exact markup), and how do you decide that something is worth an automated test at all?

T2. Unit tests

  1. What makes a good unit test: arrange-act-assert, one behaviour per test, descriptive names, deterministic (no time, randomness or network), fast. Rewrite test('cart works', …) that checks five things into focused tests.
  2. The lab's mutation testing: a test suite with 80% line coverage let the Math.round → Math.floor mutant survive because every expected total was a whole number. Explain why coverage can't measure assertion strength, and how to choose inputs that kill mutants (boundaries, non-integers, empty, maximum).
  3. Property-based testing (fast-check): write three properties for the cart totals and explain what kinds of bugs properties find that examples miss.

T3. Component tests and Testing Library

  1. Explain Testing Library's guiding principle ("the more your tests resemble the way your software is used, the more confidence they can give you") and the query priority: getByRole (with name), getByLabelText, getByPlaceholderText, getByText, getByDisplayValue, getByAltText, getByTitle, getByTestId.
  2. P1 rendered an Add button in six versions and tried four queries. getByRole('button', { name: /add paneer thali/i }) survived a class rename, a removed test id and a markup restructure, and failed when the button became a <div> or the copy changed. querySelector('.btn-primary') failed on the harmless class rename. getByTestId survived the div change. Which failures are useful, and what does that say about each query?
  3. getBy vs queryBy vs findBy; user-event vs fireEvent; why findBy/waitFor replace fixed waits (the lab: 22 of 40 runs failed with a 200 ms wait).

T4. Vitest, Jest and fake timers

  1. Compare Vitest and Jest (ESM and TypeScript support, Vite config reuse, watch mode, browser mode, compatibility API, speed). The lab found jsdom start-up was 61% of component test time: what are the options (parallel workers, happy-dom, Vitest browser mode, Playwright component testing)?
  2. P4: a debounced search test took 491 ms with real timers. With vi.useFakeTimers() it hung (timed out) in every configuration until RTL was told about the fake clock (globalThis.jest = { advanceTimersByTime: … }); then it took 23 ms, and the results were absent at 299 ms and present at 300 ms. Explain why, and the trade-offs of fake timers.
  3. Mocking with vi.fn, vi.spyOn, vi.mock (module mocks) and their risks: hoisting, mocks that drift from reality (P3), and tests that only test mocks.

T5. End-to-end tests with Playwright

  1. What should E2E tests cover (a few critical journeys against the built app: browse → add → checkout → confirmation; login; one error path), and why do teams that write hundreds of E2E tests regret it?
  2. Explain Playwright's model: auto-waiting actions, web-first assertions (await expect(locator).toBeVisible()), locators by role, test isolation with fresh browser contexts, storageState for logged-in tests, projects for browsers and devices, sharding and retries.
  3. A test fails only in CI, once in 20 runs. Walk through diagnosing it with a trace (trace: 'retain-on-failure'): what you look for (the action log, network, console, DOM snapshots, timing) and the usual root causes.

T6. Fixtures, mocking and MSW

  1. What are test fixtures (data builders like aDish({ veg: false }), Playwright fixtures for pages/users/API clients, database seeds), and why should each test create its own data?
  2. Why is mocking at the network boundary with MSW better than mocking fetch or the API module? Explain handlers, server.use overrides per test, onUnhandledRequest: 'error', and resetHandlers (the lab's "try it yourself": removing it leaks overrides between tests).
  3. P3: an MSW handler returned last year's shape (price: 180), the component rendered "Paneer thali ₹NaN", and a test asserting only the name passed. Validating the handler's data against the shared Zod schema reported dishes.0.pricePaise: Invalid input: expected number, received undefined. Design a fixture strategy that prevents mock drift.

T7. Visual regression testing

  1. What does visual regression testing catch that DOM-based tests can't (layout breaks, overflow, z-index, font and colour changes, responsive breakpoints), and what are its costs (baseline management, cross-platform rendering differences, review fatigue)?
  2. P5 compared screenshots with pixelmatch at thresholds 0, 0.1 and 0.2 (Playwright's default is 0.2): #8a4b08 → #8a4b09 changed 4,035 pixels at threshold 0 and 0 at 0.1; a visibly different #9a5b18 was also 0 at 0.1; padding 10 → 11 px gave 809 at 0.2; letter-spacing 0.2 px gave 291; border-radius 8 → 6 px gave 0 even at threshold 0, and 40–72 only with includeAA: true. Explain thresholds, anti-aliasing detection, and how to configure visual tests to catch the changes you care about.
  3. Where do visual tests run (Storybook stories with Chromatic or Percy; Playwright toHaveScreenshot in Docker for consistent fonts), and how do you keep them stable (fixed data, frozen time, disabled animations, masked dynamic regions)?

T8. Accessibility and performance testing

  1. Combine chapter 20's lessons into a testing plan: lint (jsx-a11y), role-based queries (P1), axe in component and E2E tests (about half of issues), keyboard journey tests, and manual screen-reader scripts. Where does each run and what does it catch?
  2. P7 measured LCP 10 times on the same local page: at normal CPU, median 60 ms with a range of 56–104 ms (stdev 22% of the mean); at 4× CPU throttling, median 212 ms with a range of 164–276 ms (16%). What does this variance mean for performance tests in CI, and how do you design them (budgets, medians of several runs, lab vs field data, Lighthouse CI assertions, bundle-size budgets)?
  3. Which performance checks are deterministic enough to gate merges (bundle sizes, request counts, image sizes, no render-blocking third parties) versus which should be trends (LCP, INP, TBT)?

T9. Contract testing, and frontend vs backend testing

  1. What is contract testing (consumer-driven contracts with Pact; schema-based contracts with OpenAPI/Zod; provider verification), and how does it replace slow E2E tests across teams for "does the frontend still work with the API"?
  2. How does frontend testing differ from backend testing (UI state and rendering, browsers and devices, asynchrony and timing, visual and accessibility concerns, user behaviour; backends: data, concurrency, contracts, performance under load), and what do they share (pyramid economics, deterministic tests, fixtures, CI)?
  3. A team's frontend tests are green, but production breaks after every backend deploy. Where is the gap, and what tests close it?

Programming exercises

P1. Which queries survive which refactors

Render an "Add Paneer thali" button in six versions (original, CSS class renamed, test id removed, markup restructured with an icon and spans, button turned into a div, copy changed to "Add to cart") and try four queries on each: getByRole('button', { name }), getByText, getByTestId, and querySelector('button.btn-primary'). Record which find it. Decide which failures are useful.

P2. Unit tests that kill mutants

Write unit tests for the cart totals (T2's functions), run a mutation tool (Stryker) or the lab's 30-line mutation script, and raise the score to 100% by choosing better inputs, not more tests. Add three fast-check properties. Report coverage and mutation scores before and after.

P3. Catch mock drift with schemas

Write a Menu component that fetches /menu and renders each dish's name and price in rupees from pricePaise. Test it with an MSW handler returning last year's shape (price: 180): first asserting only the name, then validating the handler's data against the shared Zod schema, then building the fixture through the schema. Record what renders and which tests fail.

Test a search box that debounces by 300 ms: once with real timers and findBy, once with Vitest fake timers. Record how long each takes, what happens with fake timers and Testing Library's default setup, and how to make it work. Assert precisely that nothing appears at 299 ms and results appear at 300 ms.

P5. Visual regression thresholds

Screenshot a button and price line, then change the background #8a4b08 → #8a4b09, to #9a5b18, padding 10 → 11 px, border-radius 8 → 6 px, and letter-spacing 0.2 px. Compare with pixelmatch at thresholds 0, 0.1 and 0.2, with and without includeAA. Then configure toHaveScreenshot so it catches the colour change and the radius change but not rendering noise.

P6. A Playwright E2E suite with fixtures, auth and traces

Write the checkout journey: log in once in a setup project (storageState), create test data through the API in a fixture (a kitchen with two dishes, a user with an empty cart), add dishes with role locators, pay with the test gateway, and assert the confirmation. Run on Chromium and a Pixel 7 emulation, with trace: 'retain-on-failure'. Introduce a flaky step (a fixed wait), make it fail in a loop of 20 runs, and fix it using the trace.

P7. Performance tests that don't flake

Measure LCP of a local page 10 times with and without 4× CPU throttling; compute median, range and standard deviation. Then set up Lighthouse CI with 5 runs and assertions, and a bundle-size budget with size-limit, and decide which checks gate merges.

P8. A contract between the menu API and the frontend

Define the menu API contract once (OpenAPI or Zod), generate TypeScript types, validate MSW fixtures against it (P3), validate real API responses against it in the backend's tests, and add a CI check that fails on breaking changes (removing pricePaise, renaming a field, making a field nullable). Alternatively, write a Pact consumer test and verify it against the provider.

P9. A test plan for one feature, with costs

For "apply a coupon at checkout", write the complete test plan: unit tests for the rules, component tests for the UI states (empty, valid, invalid, expired, network error, loading), accessibility checks, one E2E path, a contract for the coupon API, and what you deliberately won't test. Estimate run time per level using the lab's costs, and implement the component tests with MSW.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–26)

C1. A test strategy and CI pipeline for the TiffinBox frontend

Design and implement the testing strategy for the React customer app and the Angular partner portal: static analysis (TypeScript strict, ESLint with jsx-a11y and boundaries), unit and property tests for domain logic, component tests with MSW and schema-validated fixtures, axe and keyboard tests, visual tests for design-system components, a few Playwright journeys on two browsers and a phone, contract checks, performance budgets, mutation testing nightly for pricing, and flake management (quarantine with owners, trace artifacts). Define CI stages, time budgets and ownership.

Combines: Volume 1's CI and testing (ch 01, 10), TypeScript and Zod (ch 16), accessibility (ch 20's C2), UI architecture boundaries (ch 21's P7), React and Angular testing (ch 22, 23), state machines and queries (ch 25) and this chapter.

C2. Rescue a slow, flaky test suite

A frontend suite takes 45 minutes, fails about one run in three, and has 1,200 Enzyme-era tests with shallow rendering, 300 Cypress tests with cy.wait(2000), snapshot tests of whole pages, and module mocks everywhere. Plan and execute a rescue: measure (time per file, flake rates, what each test protects), delete or rewrite, migrate tools, and set rules that prevent regression. Report before/after numbers.

Combines: Volume 1's refactoring and metrics practices (ch 01, 10), this volume's React, Angular and state chapters (ch 22, 23, 25) and this chapter's techniques.

C3. Test the real-time order tracker

Write the full test set for the order tracking page (chapter 22's C2, chapter 25's T6): unit tests for the status reducer/machine, component tests with a fake EventSource and fake timers for reconnection back-off, MSW for the fallback poll, accessibility checks for the live region announcements (text changes), a Playwright test that streams a scripted SSE sequence and drops the connection, and a visual test of each status. Make all of it deterministic.

Combines: SSE and reconnection (ch 17, 19), accessibility live regions (ch 20), React effects and custom hooks (ch 22), server-state caching (ch 25) and this chapter.

What the chapter leaves out

Testing Storybook stories and design systems

Storybook stories double as test cases: interaction tests (play functions using Testing Library and userEvent), accessibility checks (the a11y addon running axe), visual tests (Chromatic or the Storybook test runner with Playwright screenshots), and composition (one story per state, reused in component tests via composeStories). For a design system, this gives each component a living specification and catches regressions in every theme.

Testing server components and full-stack apps

React Server Components and server actions are hard to unit-test in jsdom (async components, server-only modules). Approaches: test data functions and actions as plain async functions (with a test database or fakes), render server components with experimental test utilities or through the framework in integration tests, and rely on Playwright against a production build for the integration (chapter 24's P8). Next.js and React Router provide testing guidance and helpers that change between versions.

Test data management and environments

E2E and contract tests need test environments and data: ephemeral preview environments per pull request (chapter 31), seeded databases or API factories (P6's fixtures), test payment gateways and OTP bypasses that work only in test environments, cleanup of created data, and isolation between parallel runs (unique ids). Production smoke tests use synthetic accounts and must never create real orders or charges.

Testing for security and privacy

Frontend security tests include checking CSP headers and Trusted Types violations in E2E (chapter 28), XSS payloads in inputs that render user content, ensuring no secrets or personal data appear in bundles or logs, dependency scanning (npm audit, Dependabot, Socket), and checking that third-party scripts load only after consent. Privacy tests verify that analytics events respect consent and contain no personal data.

Testing culture: TDD, test reviews and ownership

Test-driven development (write a failing test first, then the code, then refactor) works well for logic and bug fixes (write the failing regression test before fixing). Reviewing tests is as important as reviewing code: check names, levels, assertions (do they assert values users see?), and determinism. A team's testing health shows in metrics like flaky rate, suite duration, escaped bugs and mutation scores on critical code, not in coverage percentage alone.

Senior exercises

S1. Set a team's frontend testing policy

Write a one-page testing policy for TiffinBox's frontend teams: required tests per change type (bug fix, new component, new page, API change), preferred queries and tools, rules (no fixed waits, no test ids without reason, no whole-page snapshots, MSW over module mocks, schema fixtures), CI gates and time budgets, flake handling, coverage and mutation targets, and who owns what.

S2. Review a test pull request

A PR adds tests for the checkout page: a Jest test that mocks useCart, usePayment and the CheckoutButton component, then asserts expect(useCart).toHaveBeenCalledWith(…); a test using container.querySelector('.css-1x2y3z'); a 400-line snapshot of the page; a Cypress test with cy.wait(3000) before clicking Pay; and an MSW handler returning { total: 189 } while the API returns totalPaise. Write the review.

S3. Decide what to do about jsdom

The team's component tests run in jsdom and miss bugs involving layout (sticky positioning, overflow, IntersectionObserver-driven lazy loading, focus scrolling) and real CSS. Options: keep jsdom and add more E2E, move component tests to Vitest browser mode, adopt Playwright component testing, or split (jsdom for logic-heavy components, real browser for layout-sensitive ones). Decide, with cost and migration considerations.

S4. Make visual testing work for a multilingual app

TiffinBox's UI ships in English, Hindi and Telugu, light and dark themes, three breakpoints and two browsers: 36 combinations per screen. Design a visual testing approach that catches real regressions (overflowing Telugu text, broken dark-mode contrast, layout shifts) without drowning reviewers in diffs.

S5. Teach testing with one bug and four tests

Prepare a 20-minute session that takes one real-world bug ("the checkout total showed ₹NaN after the API renamed price to pricePaise") and shows four tests that would or wouldn't have caught it: a unit test, a component test with a stale mock, a component test with schema fixtures, and a contract check. Use this chapter's outputs and end with five rules.