Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 132 ยท Testing and Quality

End-to-End and Accessibility Testing

Test React apps like a real user. Learn end-to-end tests with Playwright and Cypress, automated accessibility checks, keyboard and contrast tests, and how to run them in CI.

Unit and component tests tell you that each part works on its own. They cannot tell you that the whole product works: that the sign-up button is really reachable, that the server and the browser agree on a cookie, that a screen reader user can finish checkout. For that you need two more kinds of tests. End-to-end (e2e) tests drive a real browser through a real user journey. Accessibility tests check that people who use the keyboard, a screen reader or high zoom can use the same journey.

This lesson explains where each kind fits in your test suite, what the popular tools look like, and how to build the core ideas yourself. Playwright, Cypress and axe are not installed in our editor, so their code is shown read-only. But the ideas underneath (find things the way a user does, wait for the UI instead of sleeping, check names and contrast) can be written in plain JavaScript, and those versions run live below. It builds on Testing React Components and Testing Hooks, Reducers and Custom Logic.

Where e2e tests fit

Think of a pyramid. At the bottom are many fast unit tests (a reducer, a formatter). In the middle are component tests (render one component, click, assert). At the top are a few e2e tests that use the real app in a real browser.

Level Speed Confidence Flakiness Use for
Unit milliseconds one function works very low logic, reducers, utilities
Component tens of milliseconds one UI piece works low forms, widgets, states
End-to-end seconds the whole stack works highest the few journeys that make money

The trap is writing everything at the top. A suite of 400 slow e2e tests fails randomly, takes 40 minutes in CI, and the team learns to ignore red builds. Write e2e tests only for critical paths: sign up, log in, search and open a result, add to cart and pay, the one flow your business cannot afford to break. Cover the edge cases (empty list, error message, validation text) with component tests.

A good rule of thumb: if a bug here would wake someone up at night, it earns an e2e test. Everything else gets a cheaper test.

What an e2e test looks like (Playwright, read-only)

Playwright starts Chromium, Firefox or WebKit, opens your running app and acts like a person. The code below is read-only: it needs npm install -D @playwright/test, a dev server and a browser, none of which exist in our editor.

JavaScript
// tests/signup.spec.js  (Playwright, not runnable in this editor)
import { test, expect } from '@playwright/test';

test('a new visitor can create an account', async ({ page }) => {
  await page.goto('http://localhost:5173/signup');

  await page.getByLabel('Email').fill('[email protected]');
  await page.getByLabel('Password').fill('correct horse battery');
  await page.getByRole('button', { name: 'Create account' }).click();

  await expect(page.getByRole('heading', { name: 'Welcome, Ada' })).toBeVisible();
});

Three habits in these few lines make e2e tests last:

  1. Locate like a user. getByLabel and getByRole find elements by what a person or screen reader perceives, not by .btn-primary > span:nth-child(2). When you restyle the page, the test keeps passing. It also means the test fails when the label is missing, which is an accessibility bug caught for free.
  2. Never sleep. There is no await sleep(2000). The expect(...).toBeVisible() assertion retries until the element appears or a timeout expires. Playwright also waits for an element to be visible and enabled before it clicks.
  3. Each test owns its data. The test creates its own user (or resets the database through an API) so tests can run in parallel and in any order.

Cypress follows the same ideas with a different style: commands are queued and retried automatically.

JavaScript
// cypress/e2e/signup.cy.js  (Cypress, not runnable in this editor)
describe('sign up', () => {
  it('creates an account', () => {
    cy.visit('/signup');
    cy.findByLabelText('Email').type('[email protected]');
    cy.findByLabelText('Password').type('correct horse battery');
    cy.findByRole('button', { name: 'Create account' }).click();
    cy.findByRole('heading', { name: /welcome, ada/i }).should('be.visible');
  });
});

(findByLabelText comes from the Testing Library plugin for Cypress.) Choose either tool; both are good. Playwright has built-in parallelism and three browser engines. Cypress has a friendly interactive runner.

Fake the network, not the user

An e2e test that depends on a live third-party payment API will fail whenever that service is slow. Tools let you intercept requests and answer them yourself.

JavaScript
// Playwright: answer the products request with fixed data
await page.route('**/api/products', (route) =>
  route.fulfill({ json: [{ id: 1, name: 'Notebook', price: 4 }] })
);

Mock the things you do not own (payments, email, maps). Keep your own backend real for at least a few tests, because those are the ones that catch contract mismatches.

Build the idea: a tiny e2e driver

Here is the same style in plain JavaScript so you can see how it works. We make a small "user" with click, type and a waitFor that polls the page until an assertion stops throwing. The app saves a note after a short delay, exactly like a request to a server would take time, and the test never uses a fixed sleep.

A user driver with waitFor

Read the log: steps 1 to 3 pass because waitFor keeps checking until the UI catches up with the user. Step 4 shows a failure message after the 100 ms budget. Real tools do the same thing with better locators, smarter timeouts and screenshots on failure. The takeaway is the shape of a robust test: act, then wait for a visible result, never for a number of milliseconds.

Why accessibility belongs in your tests

Roughly one in six people lives with a disability, and many more have a temporary one (a broken arm, a bright screen outdoors, a noisy room). Accessible UIs also tend to be easier for search engines, voice control and automated tests, because they expose clear names and roles. In many countries accessibility is a legal requirement for public and commercial sites.

The standard to aim at is WCAG (Web Content Accessibility Guidelines), usually level AA. Its four principles are that content must be perceivable, operable, understandable and robust. For React developers the daily work boils down to a short list:

  • Every image has an alt (empty alt="" when decorative).
  • Every form control has a label.
  • Every button and link has an accessible name (visible text, or aria-label for icon-only buttons).
  • Everything works with the keyboard, with a visible focus indicator and a sensible order.
  • Text has enough contrast.
  • Headings form an outline, and landmarks (main, nav) exist.
  • Dynamic changes are announced (status messages use role="status" or aria-live).

See Accessibility for how to build these correctly. This lesson is about catching mistakes automatically.

Automated tools find only a fraction of accessibility problems, commonly estimated at 30 to 50 percent. They can tell you an input has no label. They cannot tell you whether the label is helpful, or whether the focus order makes sense. Treat automation as a safety net, and still test by hand with the keyboard and a screen reader.

Automated accessibility checks with axe (read-only)

axe-core is the engine behind most accessibility tooling (Lighthouse, browser extensions, linters). It inspects the DOM against a library of rules and returns violations with a severity, a help link and the failing elements. You rarely call it directly. You use a wrapper in your test runner.

JavaScript
// Playwright + axe  (read-only: needs @axe-core/playwright)
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

test('the checkout page has no detectable accessibility violations', async ({ page }) => {
  await page.goto('http://localhost:5173/checkout');

  const results = await new AxeBuilder({ page }).withTags(['wcag2a', 'wcag2aa']).analyze();

  expect(results.violations).toEqual([]);
});
JavaScript
// Component test with jest-axe  (read-only: needs jest-axe and Testing Library)
import { render } from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';
import { SignupForm } from './SignupForm';

expect.extend(toHaveNoViolations);

test('SignupForm has no accessibility violations', async () => {
  const { container } = render(<SignupForm />);
  expect(await axe(container)).toHaveNoViolations();
});

Put the component-level check next to your normal component tests (it is cheap) and run page-level checks in e2e on your most important routes. Also add eslint-plugin-jsx-a11y to your linter (Linting, Formatting and Code Quality) so many mistakes never reach a test at all.

Build the idea: a mini accessibility audit

To see what such rules do, here is a small audit function. It walks a container and reports four classic problems: images without alt, form controls without an accessible name, buttons without a name, and skipped heading levels. It runs on a deliberately bad form and on a repaired one.

A hand-made accessibility audit

The broken form has four problems and the fixed one has none. Notice the fixes: a wrapping <label> gives the input its name (a placeholder is not a label, it disappears as soon as you type), alt="" marks the picture as decoration so screen readers skip it, the heading goes from h2 to h3 without a gap, and the icon-only button gets an aria-label because the SVG is hidden from assistive technology.

Real engines like axe are far more complete, since they implement the full name computation from the accessibility standards and hundreds of rules. Still, running this by hand shows you that accessibility checks are just inspections of the DOM you already have, which is why they are cheap to add to component tests.

Contrast is arithmetic

Contrast is one rule you can compute exactly. WCAG defines the contrast ratio between two colors from their relative luminance. AA requires at least 4.5:1 for normal text and 3:1 for large text (about 24 px, or 19 px bold). Large text and UI parts such as input borders use 3:1.

Checking color contrast

Light gray #999999 on white, a very common "subtle" design choice, fails AA, while #595959 passes. Orange buttons with white text often fail too. A design system can run this check once over all its color tokens, and a failing pair stops the build before it reaches users.

Test the keyboard

Many users never touch a mouse. Two bugs account for most keyboard failures: a clickable element that cannot receive focus (a <div onClick>), and a positive tabindex that scrambles the order. You can test the first one with a list of focusable elements, because browsers decide focusability by tag, attribute and tabindex.

Listing the keyboard tab order

In the broken toolbar the Italic button (with tabIndex={3}) jumps in front of Bold, and the div "button" is missing from the order entirely, so keyboard users cannot press it. In the fixed version all three live buttons appear in reading order and the disabled one is skipped, which is correct. A real e2e check does the same thing with the keyboard: await page.keyboard.press('Tab') and then await expect(page.getByRole('button', { name: 'Bold' })).toBeFocused().

Use native elements (<button>, <a href>, <input>) and you get focus, Enter/Space activation and the right role for free. Avoid tabindex values above 0. Use tabIndex={-1} only to move focus into something programmatically (see Refs).

Visual regression tests

A visual regression test takes a screenshot of a page or component and compares it with an approved baseline image. If pixels differ beyond a small threshold, the test fails and shows a diff.

JavaScript
// Playwright (read-only)
await expect(page).toHaveScreenshot('pricing-page.png', { maxDiffPixelRatio: 0.01 });

They catch what no other test does (a CSS change that breaks the layout), but they are touchy: fonts, animations, dates and ads change pixels. Freeze the clock, disable animations, wait for fonts, mask dynamic regions, and run them in the same container image locally and in CI, otherwise screenshots differ by operating system. Hosted services (Chromatic, Percy) manage baselines and review for you. Use visual tests for a design system or a few key pages, not for every screen.

Running it all in CI

Tests only protect you if they run on every change. A typical pipeline runs fast checks first and slow ones last, and stops early on failure.

TEXT
# .github/workflows/test.yml (read-only, abbreviated)
name: test
on: [pull_request]
jobs:
  checks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 24, cache: npm }
      - run: npm ci
      - run: npm run lint
      - run: npm run typecheck
      - run: npm test
      - run: npx playwright install --with-deps chromium
      - run: npm run build
      - run: npx playwright test
      - uses: actions/upload-artifact@v4
        if: failure()
        with: { name: playwright-report, path: playwright-report/ }

Practical tips:

  • Run e2e against a production build (vite preview, or your deployed preview URL), not the dev server, so you test what users get.
  • Upload traces, screenshots and videos on failure. A failing e2e test you cannot see is almost impossible to debug.
  • Shard and parallelize when the suite grows, and retry once in CI only to report flaky tests, never to hide them. Fix or delete a flaky test; do not tolerate it.
  • Keep the suite fast. Under ten minutes is a good target. Beyond that, people stop waiting for it.
  • Block merges on failures. Make the check required in your repository settings.

Common mistakes

  • Selecting by CSS class or test id when a role or label exists. Use getByRole first, getByLabel and getByText next, and a data-testid only as a last resort.
  • Fixed sleeps (waitForTimeout(3000)). They make tests both slow and flaky. Wait for a condition.
  • Tests that depend on each other's data or order.
  • Treating a green axe report as "the site is accessible".
  • Using a placeholder as the only label, or removing the focus outline without a replacement.
  • Testing every edge case end to end instead of in cheaper tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which kind of test is the best fit for a rare validation message on a single field?

    Edge cases like validation text belong in fast component tests. Keep slow end-to-end tests for the few critical journeys.
  2. 2. Why is getByRole('button', { name: 'Save' }) better than selecting .btn-primary?

    Role and name queries mirror how people find controls. A refactor of class names does not break them, and an unnamed button makes the test fail, which reveals an accessibility bug.
  3. 3. In the user driver demo, what did waitFor replace?

    waitFor retries the assertion until it passes or a timeout is reached, so the test is as fast as the UI and does not guess how long saving takes.
  4. 4. Which statement about automated accessibility tools like axe is true?

    Automation finds a portion of issues, often estimated at 30 to 50 percent. Manual checks with the keyboard and a screen reader are still needed.
  5. 5. In the contrast demo, why does #999999 text on white fail WCAG AA for normal text?

    AA needs at least 4.5:1 for normal text, and light gray on white falls short of that. Darker gray such as #595959 passes.

Summary

  • Use a testing pyramid: many unit tests, some component tests, a few end-to-end tests for critical journeys.
  • Write e2e tests with Playwright or Cypress: locate elements by role and label, wait for conditions instead of sleeping, give each test its own data and mock only services you do not own.
  • Accessibility basics to enforce: alt text, labels, accessible names, keyboard access, contrast, heading order and announced updates.
  • Add axe (component tests, e2e) and eslint-plugin-jsx-a11y, but keep manual keyboard and screen reader checks, because automation finds only part of the problems.
  • Visual regression tests catch layout changes; make them deterministic and use them sparingly.
  • Run lint, types, unit, build and e2e in CI, test the production build, keep traces for failures and fix flaky tests instead of retrying them.

Next: Debugging React Apps