Frontend Testing Strategy

A good test suite lets a team ship many times a day without fear. This guide shows which frontend tests to write and where each one draws its boundary. It also shows how to keep the suite fast and free of flaky failures.

Frontend system design · patterns

Design a test strategy for a large web app. It must catch real bugs early, run in minutes in CI, and stay trusted by the team.

Correctness contract: A green build means the main user journeys work, the UI is accessible, and it is not slower than budget. A red build always points at a real problem, not at random noise.

You know JavaScript or TypeScript and one component framework, such as React. You have run a test command before. Tool names reflect common choices in 2026: Vitest or Jest, Testing Library, Mock Service Worker, Playwright, and axe-core. The ideas apply to other tools too.

Frontend code is hard to test well. It runs in many browsers, on many screen sizes, with real timing and real networks. It depends on a backend that changes on its own schedule. It has visual and accessibility requirements that a simple assertion cannot express. Teams often respond with one of two bad extremes. Some write thousands of tiny unit tests that check implementation details and break on every refactor. Others write a few huge end-to-end tests that take an hour and fail at random. A good strategy sits between them. It picks the cheapest test that gives real confidence for each risk. This guide walks through each layer, what it is good at, and how the layers fit together in CI.

Contents

  1. Concepts to understand first
  2. 1. Pyramid versus trophy
  3. 2. Unit tests
  4. 3. Component tests with Testing Library
  5. 4. Mocking the network and contract tests
  6. 5. End-to-end tests with Playwright
  7. 6. Visual regression
  8. 7. Accessibility testing
  9. 8. Performance budgets in CI
  10. 9. Controlling flaky tests
  11. 10. Testing real-time and offline behavior
  12. 11. Failure modes
  13. 12. Trade-offs
  14. 13. Interview angle
  15. 14. Summary
  16. 15. Common mistakes
  17. Worked example: a broken checkout caught in CI
  18. Code lab: retry logic with a mocked network and fake timers
  19. Check yourself
  20. Key terms
  21. Further reading

Concepts to understand first

Test boundary

Every test decides what is real and what is fake. That line is its boundary. A wider boundary gives more confidence but runs slower and fails for more reasons.

Example. A component test renders a real form and real child components, but fakes the network. An end-to-end test uses a real browser, real server, and real database.

Limit. Anything outside the boundary is untested by that test. If every test fakes the API, nothing proves the client and server agree.

Test doubles

A test double replaces a real dependency. A stub returns fixed answers. A mock also records calls so you can assert on them. A fake is a simple working version, such as an in-memory database.

Example. A stubbed fetch always returns a 200 with two items. A fake server in memory stores items you POST and returns them on GET.

Limit. A double can drift from the real thing. Tests stay green while production breaks.

jsdom versus a real browser

jsdom is a JavaScript version of the DOM that runs in Node. It is fast and needs no browser. It does not do layout, paint, or real CSS. Real browsers, run by Playwright, do everything but cost more time.

Example. In jsdom, getBoundingClientRect() returns all zeros. A test that checks whether a tooltip fits on screen must run in a real browser.

Limit. Browser runners in component mode, such as Vitest browser mode or Playwright component tests, close the gap but add setup.

Flaky test

A flaky test passes and fails on the same code without any change. The cause is usually timing, shared state, test order, or an outside service.

Example. A test clicks "Save" and checks for a toast after a fixed 500 ms wait. On a busy CI machine the request takes 700 ms and the test fails.

Limit. Automatic retries hide flakiness. They do not remove it, and real race bugs can hide behind them.

Contract

A contract is the agreed shape of messages between two systems: fields, types, status codes, and error formats. A contract test checks that one side keeps its promise, without running the other side.

Example. The cart API promises { items: [{ id, qty, price }] } and a 409 with { code: 'OUT_OF_STOCK' }. Both client mocks and server tests check against that schema.

Limit. A contract checks shape, not behavior. Correct JSON can still hold wrong prices.

Budget

A budget is a hard limit that CI enforces, such as bundle size, Lighthouse score, or test run time. Passing a budget is a check like any test.

Example. The main route's JavaScript must stay under 170 KB compressed. A pull request that adds a 60 KB date library fails the build.

Limit. Lab budgets run on fixed hardware. They catch regressions but do not prove real users are fast.

1. Pyramid versus trophy

The test pyramid has many unit tests at the bottom and fewer integration tests in the middle. Very few end-to-end tests sit at the top. The logic is cost. Unit tests run in milliseconds and pinpoint failures. End-to-end tests take seconds to minutes and fail for many reasons.

The testing trophy, popularized by Kent C. Dodds, changes the weights for frontend work. It adds static analysis at the base, such as TypeScript and ESLint. It puts the largest share in integration tests, meaning component tests that render several components together. Unit tests and end-to-end tests are smaller slices. The argument is that a frontend's bugs live in how pieces connect: props, state, events, and data loading. Pure unit tests miss those.

Test layers from static analysis through unit, component, contract, end-to-end, visual, accessibility, and performance checks, showing what each one fakes
Each layer and its boundary. Lower layers fake more and run faster. Higher layers use more real parts and catch wiring bugs.

A practical mix

For a typical product app, a healthy suite might look like this:

Intuition

Ask, "If this test fails, what do I learn, and how fast?" A unit test says "this function is wrong" in 5 ms. An end-to-end test says "something in checkout is broken" after 40 seconds. Use the narrow test where it can catch the bug. Use the wide test only for what narrow tests cannot see.

2. Unit tests

A unit test checks one small piece of logic in isolation. In frontend code the best targets are pure functions with clear inputs and outputs.

Good targets

Rules that keep them useful

Mistake

Mocking everything a module imports. If a test of CartSummary mocks formatPrice, useCart, and every child component, it only proves that your mocks return what you told them to. It breaks on every refactor and catches no real bug.

3. Component tests with Testing Library

Component tests render real UI and interact with it the way a user would. Testing Library is the standard tool. Its guiding idea is: the more your tests resemble the way your software is used, the more confidence they give.

Query by role and name

Find elements the way a user or a screen reader would. Prefer getByRole('button', { name: 'Add to cart' }). Then use getByLabelText for form fields and getByText for content. Use getByTestId only as a last resort. Querying by role has a second benefit. If the test cannot find a button by its accessible name, a screen reader user cannot either. The test becomes a light accessibility check for free.

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

test('adding an item updates the cart count', async () => {
  const user = userEvent.setup()
  render(<ProductPage productId="p1" />)

  await user.click(await screen.findByRole('button', { name: 'Add to cart' }))

  expect(await screen.findByRole('status')).toHaveTextContent('1 item in cart')
})

Async the right way

userEvent versus fireEvent

fireEvent.click dispatches one DOM event. A real click produces pointerdown, mousedown, focus change, pointerup, mouseup, and click. user-event simulates that full sequence. It also checks that the element is not disabled and not hidden by pointer-events: none. Use it by default. Typing with user.type fires key events per character, which exercises input masks and debounced search.

What to render

Render a whole screen or feature with its real children, real state store, and real router. Provide a test wrapper that sets up providers: theme, i18n, query client, and router at a given URL. Fake only the network and true outside services like payment SDKs. This gives integration-level confidence at near unit-test speed, often 20 to 100 ms per test in jsdom.

Tip

Create a fresh query client and store for each test. A shared cache between tests causes order-dependent failures, which are one of the most common sources of flakiness in component suites.

4. Mocking the network and contract tests

Where you cut the network matters. If you mock your own api.getCart() function, the test skips your fetch wrapper, headers, error parsing, and retry logic. Those are exactly where bugs hide.

Mock Service Worker

Mock Service Worker (MSW) intercepts requests at the network level. In the browser it uses a real service worker. In Node it hooks the request modules that fetch uses. Your app code calls the real fetch with the real URL. MSW returns a response from a handler you define.

import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

export const handlers = [
  http.get('/api/cart', () => HttpResponse.json({ items: [], version: 1 })),
  http.post('/api/cart/items', async ({ request }) => {
    const body = await request.json()
    return HttpResponse.json({ items: [{ id: body.productId, qty: 1 }], version: 2 })
  }),
]

export const server = setupServer(...handlers)
// in test setup: beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
// afterEach(() => server.resetHandlers()), afterAll(() => server.close())

Override a handler in one test to simulate failure: server.use(http.post('/api/cart/items', () => new HttpResponse(null, { status: 503 }))). Now you can test the error state, the retry, and the toast. The setting onUnhandledRequest: 'error' makes any unmocked request fail the test, so tests never reach a real server by accident.

The same handlers can run in the browser during local development and in Storybook. One set of mocks then serves three uses, which reduces drift.

Keeping mocks honest

Mocks drift. The backend renames qty to quantity. Every frontend test still passes, and production breaks. Contract tests stop this.

Interview

Interviewers often ask, "How do you know your mocks match the API?" Name a concrete mechanism. Examples are types generated from a schema, schema checks on mock responses, or consumer-driven contracts in backend CI.

5. End-to-end tests with Playwright

End-to-end (E2E) tests drive a real browser through a real deployed app. They are the only layer that proves the whole system works together: build, CDN, auth, API, database, and browser.

Why Playwright

Playwright runs Chromium, Firefox, and WebKit with one API. Its locators wait for elements to be visible, enabled, and stable before acting. That auto-waiting removes most manual waits. Each test gets a fresh browser context, which is like a new incognito profile, in a few milliseconds. Tests run in parallel workers and can be split across CI machines with --shard=1/4. On failure it records a trace with DOM snapshots, network calls, and console logs, which you open in the trace viewer.

import { test, expect } from '@playwright/test'

test('guest can buy one item', async ({ page }) => {
  await page.goto('/product/p1')
  await page.getByRole('button', { name: 'Add to cart' }).click()
  await page.getByRole('link', { name: 'Cart' }).click()
  await page.getByRole('button', { name: 'Checkout' }).click()
  await page.getByLabel('Email').fill('guest@example.com')
  await page.getByRole('button', { name: 'Place order' }).click()
  await expect(page.getByRole('heading', { name: 'Thank you' })).toBeVisible()
})

Choosing what to cover

E2E tests are expensive, so pick journeys by business risk. Ask: if this broke for an hour, how much would it cost? Sign up, log in, search, checkout, and payment usually top the list. Do not test every validation message in E2E. Component tests do that faster.

Test data and isolation

Run time math

Suppose 40 journeys average 25 seconds each in one browser. That is about 17 minutes in a single worker. With 4 workers per machine and 4 shards, it drops to about 1 minute plus startup. Running three browser engines triples the cost. A common choice is Chromium on every pull request, and all three engines nightly or before release.

Mistake

Using CSS selectors like .btn-primary > span:nth-child(2). A design change breaks every test. Use role and label locators. Add data-testid only where no accessible name exists.

6. Visual regression

A test can pass while the page looks broken. A CSS change can push a button off screen, overlap text, or swap a color. Assertions on text cannot see that. Visual regression tests compare screenshots.

How it works

  1. Render a component state or page in a real browser at fixed viewport sizes, such as 375, 768, and 1280 pixels wide.
  2. Take a screenshot. Playwright does this with await expect(page).toHaveScreenshot().
  3. Compare it pixel by pixel with an approved baseline image.
  4. If more than a threshold of pixels differ, fail and show a diff image. A human approves the new baseline or fixes the bug.

Making screenshots stable

Screenshot each component state in Storybook rather than every full page. A design system with 200 components and 4 states each gives 800 small, focused images. A change to the button style then shows exactly which components moved.

Tip

Treat baseline approval as code review. A reviewer should look at every changed image. Approving 300 diffs in one click because "it is probably the font" is how visual bugs ship.

7. Accessibility testing

Accessibility bugs block real users from your product. Many are easy to detect automatically. The rest need manual checks with a keyboard and a screen reader.

Automated checks with axe

axe-core is a rules engine that scans the DOM for common WCAG failures. It finds missing labels, low contrast, invalid ARIA, missing alt text, and duplicate ids. Run it in two places.

Automated tools find a meaningful share of issues, often cited as roughly 30 to 50 percent. They cannot judge whether alt text is useful, whether focus order makes sense, or whether a custom widget is usable with a screen reader.

Keyboard and focus tests

Write explicit tests for keyboard behavior. They catch the bugs axe cannot.

await page.getByRole('button', { name: 'Delete project' }).click()
const dialog = page.getByRole('dialog', { name: 'Delete project?' })
await expect(dialog.getByRole('button', { name: 'Cancel' })).toBeFocused()
await page.keyboard.press('Escape')
await expect(dialog).toBeHidden()
await expect(page.getByRole('button', { name: 'Delete project' })).toBeFocused()
Intuition

Automated accessibility checks are like a spell checker. They catch typos fast and reliably. They cannot tell you whether the essay makes sense. A short manual screen reader pass on each new feature is the "read it aloud" step.

8. Performance budgets in CI

Performance regressions creep in one small pull request at a time. Nobody notices a 10 KB addition. Twenty of them add 200 KB and a second of load time on a mid-range phone. Budgets stop the creep.

Bundle size budgets

Measure compressed size per route entry, not just the total. Tools such as size-limit or a bundler plugin report sizes and fail when a limit is crossed. A worked number: on a mid-range phone, parsing and compiling JavaScript costs very roughly 1 ms per KB of compressed code, depending on the device. A 170 KB budget for the main route keeps that under about 200 ms. Post the size change as a comment on each pull request so authors see the cost of a new dependency before merge.

Lab metrics with Lighthouse CI

Lighthouse CI runs Lighthouse on key URLs several times and asserts on the results. Assert on metrics, not only the overall score. For example: LCP under 2.5 s and Total Blocking Time under 200 ms with mobile throttling. Run 3 to 5 times and use the median. A single Lighthouse run can vary by 10 to 20 percent.

Custom timing tests

For app-specific flows, measure your own marks in Playwright. Read performance.getEntriesByName('search-results-visible') after a search. Fail if it exceeds the budget. Run on a fixed machine type with CPU throttling through the Chrome DevTools Protocol, such as 4x slowdown. Compare against the main branch's last result, not against an absolute number alone.

Mistake

Setting budgets far above current numbers "to be safe". A budget that never fails is decoration. Set it close to today's value, and lower it after each optimization so gains are locked in.

9. Controlling flaky tests

Flaky tests destroy trust. When a test fails at random, people re-run the build until it passes. Soon they ignore real failures too. At scale the math is harsh. Take 500 E2E tests, each with a 0.2 percent chance of random failure. A full run then fails about 63 percent of the time with no real bug.

Common causes

A process, not just fixes

  1. Detect. Record every test result with its commit. A test that both passed and failed on the same commit is flaky by definition.
  2. Quarantine. Move it to a non-blocking job at once, with an owner and a ticket. The main build stays trusted.
  3. Reproduce. Run it 100 times in a loop, for example with Playwright's --repeat-each=100, under CPU throttling. Use the trace viewer on the failures.
  4. Fix the cause. Replace sleeps with web-first assertions. Isolate data. Mock outside services.
  5. Return it. Run it many times green before moving it back to the blocking suite.

Retries are a tool, not a fix. One retry in CI can absorb rare infrastructure noise. But mark any test that passed only on retry as flaky in your report. Never set retries to 3 and forget. That hides real race conditions that users will also hit.

Tip

Run the full suite in random order now and then, with a fixed seed you can replay. Order-dependent tests show up within a few runs.

10. Testing real-time and offline behavior

Real-time and offline features are timing-heavy. They are also where tests get flaky fastest. The key is to control time and the network yourself, not to wait for them.

WebSockets and server push

Fake timers for reconnect and backoff

A reconnect loop with 1, 2, 4, and 8 second delays would take 15 seconds to test in real time. With fake timers, the test advances the clock instantly. vi.useFakeTimers() in Vitest, or mock.timers in node:test, replaces setTimeout. The test then calls advanceTimersByTime(1000) and checks that one reconnect attempt happened. The code lab shows this pattern.

Offline in the browser

Interview

When you describe an offline or real-time design, finish with how you would test it. Mention fake timers for backoff, a scripted fake server for ordering and duplicates, and a browser test that flips offline and online. It shows you have shipped such features, not only drawn them.

CI pipeline for a pull request with static checks, unit and component tests, contract checks, build with size budget, preview deploy, end-to-end, visual, accessibility, and Lighthouse checks
A pull request pipeline. Fast checks run first and fail early. Slower browser checks run in parallel against a preview deploy.

11. Failure modes

12. Trade-offs

Confidence versus speed

Each step outward, from unit to component to E2E, adds real parts and confidence. Each also adds run time and new reasons to fail. Push every check to the lowest layer that can catch the bug.

jsdom versus real browser for components

jsdom is fast and simple, but it cannot test layout, scroll, or real focus behavior in all cases. Browser-mode component tests are more faithful but slower to start. Many teams use jsdom by default and browser mode for layout-heavy widgets.

Mocks versus real backends

Mocks are fast, stable, and let you test rare errors. Real backends catch integration bugs. Use mocks with contract checks for most tests, and a small set of E2E journeys on a real stack.

Coverage numbers versus useful tests

A coverage target, such as 80 percent of lines, finds untested files. It does not prove tests assert anything useful. A test that renders a component and checks nothing gets full coverage. Track coverage as a hint and review test quality in code review.

13. Interview angle

Testing questions appear on their own ("How would you test this?") and at the end of design rounds. Structure the answer by risk.

  1. Minutes 0 to 3. Name the main risks: wiring bugs, API drift, visual breakage, accessibility, performance, and timing in real-time features.
  2. Minutes 3 to 8. Static checks and unit tests for pure logic. Mention fake timers and seeded randomness.
  3. Minutes 8 to 15. Component tests with Testing Library and MSW. Query by role. Explain why you mock at the network layer.
  4. Minutes 15 to 20. Contract testing to keep mocks honest.
  5. Minutes 20 to 28. E2E with Playwright for critical journeys. Data isolation, sharding, and run time math.
  6. Minutes 28 to 35. Visual, accessibility, and performance budgets as CI gates.
  7. Minutes 35 to 45. Flake process and how you would test the feature's real-time or offline paths.
Interview

Use numbers. Say "1,500 component tests in 3 minutes" and "40 journeys in 6 minutes on 4 shards". Numbers show you have run a real suite.

14. Summary

15. Common mistakes

Worked example: a broken checkout caught in CI

A developer opens a pull request that renames the cart field qty to quantity in the frontend to match a new API version. Follow the pipeline.

  1. Static checks run first, in 40 seconds. The generated API types come from the new OpenAPI schema. TypeScript passes, because the frontend now uses quantity.
  2. Unit and component tests run in 3 shards, about 2 minutes. MSW handlers still return qty. A schema check in the test setup validates every mock response against the OpenAPI file. It fails: "response for GET /api/cart is missing required property quantity".
  3. The developer updates the MSW fixtures. Component tests now pass. One test, "cart shows total for 3 items", also failed. The total still used the old field in one place.
  4. The build step runs size-limit. The checkout route is 168 KB against a 170 KB budget. It passes, and the bot comments "+0.3 KB".
  5. A preview deploy starts. Playwright runs 40 journeys on 4 shards in Chromium against the preview, which talks to a staging API.
  6. The "guest can buy one item" journey fails. The trace viewer shows POST /api/cart/items returned 400 with "unknown field quantity". Staging still runs the old API version.
  7. The team learns the backend change is not deployed yet. The frontend must handle both shapes during rollout. The developer adds a mapping layer that accepts either field and sends the field the server version expects.
  8. The pipeline re-runs. E2E passes. axe scans of the cart and checkout pages show no violations. Visual snapshots of the cart line item show no diff.
  9. Lighthouse CI on /checkout reports median LCP 2.1 s and TBT 140 ms over 3 runs, within budget.
  10. The pull request merges. Without the schema check and the real-stack E2E, the rename would have shipped and broken checkout for every user until the backend caught up.

Code lab: retry logic with a mocked network and fake timers

This test file checks a fetchWithRetry helper. It injects a mock fetch that returns two 503 responses and then a 200. It uses node:test fake timers, so the 200 ms and 400 ms backoff delays pass instantly. A second test proves that a 404 is not retried. Save it as retry.test.mjs and run node --test retry.test.mjs with Node 20 or newer. No packages are needed.

// A unit test with a mocked network and fake timers. No real waiting.
// Run with: node --test retry.test.mjs (Node 20 or newer)
import { test, mock } from 'node:test'
import assert from 'node:assert/strict'

export async function fetchWithRetry(url, { fetchImpl, retries = 3, baseMs = 200 }) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetchImpl(url)
    if (res.status < 500 || attempt === retries) return res
    const delay = baseMs * 2 ** attempt
    await new Promise((resolve) => setTimeout(resolve, delay))
  }
}

test('fetchWithRetry retries 503 and then succeeds', async () => {
  mock.timers.enable({ apis: ['setTimeout'] })
  const replies = [{ status: 503 }, { status: 503 }, { status: 200 }]
  const fetchImpl = mock.fn(async () => replies.shift())

  const pending = fetchWithRetry('/api/items', { fetchImpl })
  for (const ms of [200, 400]) {
    await new Promise(setImmediate)   // let the failed attempt settle
    mock.timers.tick(ms)              // jump the clock, do not sleep
  }
  const res = await pending

  assert.equal(res.status, 200)
  assert.equal(fetchImpl.mock.callCount(), 3)
  mock.timers.reset()
})

test('fetchWithRetry does not retry a 404', async () => {
  const fetchImpl = mock.fn(async () => ({ status: 404 }))
  const res = await fetchWithRetry('/api/missing', { fetchImpl })
  assert.equal(res.status, 404)
  assert.equal(fetchImpl.mock.callCount(), 1)
})

Both tests pass in a few milliseconds even though the code "waits" 600 ms in total. Try changing the replies to three 503 responses and a 200, and see the first test fail because the default retries limit is 3. The same pattern works in Vitest with vi.useFakeTimers() and vi.advanceTimersByTimeAsync().

Check yourself

  1. Why does the testing trophy put the most weight on integration tests for frontends?
    Answer

    Most frontend bugs live in how pieces connect: props, state, events, and data loading. Component-level integration tests exercise that wiring at near unit-test speed, while pure unit tests miss it and E2E tests are slow.

  2. Why prefer getByRole('button', { name: 'Save' }) over getByTestId('save-btn')?
    Answer

    It finds the element the way users and assistive technology do. It survives markup refactors, and it fails if the button loses its accessible name, which is a real accessibility bug.

  3. What is wrong with mocking api.getCart() directly in component tests?
    Answer

    It skips the real fetch wrapper, headers, error parsing, and retries, which is where many bugs live. Mocking at the HTTP layer with MSW keeps that code under test.

  4. All frontend tests pass, but production breaks after a backend rename. Which test type was missing?
    Answer

    A contract test. Validating mock responses against a shared schema, or running consumer-driven contracts in the backend pipeline, would have caught the drift.

  5. 500 E2E tests each have a 0.2 percent random failure rate. How often does the full run fail with no real bug?
    Answer

    The chance all pass is 0.998 to the power 500, about 0.37. So about 63 percent of runs fail. This is why each test must be nearly perfectly stable.

  6. How do you test a reconnect loop with 1, 2, 4, and 8 second backoff without waiting 15 seconds?
    Answer

    Inject a fake socket and use fake timers. Advance the clock by each delay and assert that one reconnect attempt happened after each step.

  7. Why should screenshot tests run inside a pinned container image?
    Answer

    Fonts, anti-aliasing, and browser versions differ across machines. A pinned image makes rendering identical, so diffs reflect real UI changes, not environment noise.

Key terms

Test pyramid
A model with many unit tests, fewer integration tests, and few end-to-end tests.
Testing trophy
A model that adds static analysis and puts most weight on integration tests.
Testing Library
A family of tools that query and interact with UI the way a user would.
user-event
A Testing Library package that simulates full user interaction sequences.
MSW
Mock Service Worker, which intercepts network requests and returns mock responses.
Contract test
A test that checks one side of an API keeps the agreed request and response shape.
Playwright
A browser automation framework for Chromium, Firefox, and WebKit with auto-waiting locators.
Browser context
An isolated browser profile in Playwright with its own cookies and storage.
Visual regression
Comparing screenshots against approved baselines to catch unintended visual changes.
axe-core
An automated engine that checks the DOM against accessibility rules.
Performance budget
A hard limit on size or timing that fails the build when exceeded.
Flaky test
A test that passes and fails on the same code without changes.
Quarantine
Moving a flaky test to a non-blocking job until it is fixed.
Fake timers
Test doubles for setTimeout and clocks that let tests advance time instantly.

Further reading

Primary references