Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 3

End-to-End Journeys with Playwright

Drive a real browser through a checkout journey with resilient locators and web-first assertions, gate accessibility with axe-core, and keep journeys reliable with fixtures.

Contentsand lesson path

What you will learn

  • Write Playwright end-to-end tests for critical user journeys with resilient locators, web-first assertions and automated axe accessibility scans.

Prerequisites: React Components & State

01. The problem

Component tests prove behaviour inside one component in a simulated DOM. They cannot see the built bundle, the routing, the real network stack, or the way styles and scripts interact in a real browser. End-to-end tests close that gap: Playwright launches a real browser — Chromium, Firefox or WebKit — visits your running application and drives it the way a person would: click, type, read.

The journey to prove here is the smallest meaningful slice of a checkout: open the page, read the order summary, enter a card number, pay, and see the confirmation. Choose journeys the same way. A few that cross every layer of the product are worth more than many that re-test what component suites already cover. Plus one gate that many frontend teams add to their journeys: an automated accessibility scan.

02. Step 1: project and config

Playwright's config declares where tests live, which server to start, and what to record when a test fails. The webServer entry starts the application automatically — here a tiny static server standing in for a preview build; in a real project it is your dev server or the built app — and waits for its port before running any test:

TypeScript · playwright.config.ts
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,
    reuseExistingServer: false,
  },
});

trace: 'retain-on-failure' is deliberate: when a test fails, Playwright keeps a trace — an interactive record of every action, DOM snapshot, network request and console message — which you can open with npx playwright show-trace. It is the first thing to look at when a journey fails, long before adding a sleep. If a browser is missing on your machine, npx playwright install chromium fetches it once.

03. The page under test

The tests in this lesson drive the small checkout page below, served from public/ by the same small server.mjs that the lab prints; the project's package.json has "type": "module". It was checked with Playwright 1.64.1 (Chromium 156) and @axe-core/playwright 4.14.1. The page has two buttons on purpose, and its status line appears 300 ms after a payment:

HTML · public/checkout.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Checkout</title>
  <script type="module">
    const form = document.querySelector('form');
    const pay = document.getElementById('pay');
    form.addEventListener('submit', (event) => {
      event.preventDefault();
      pay.disabled = true;
      setTimeout(() => {
        document.getElementById('status').textContent = 'Payment sent';
      }, 300);
    });
  </script>
</head>
<body>
  <main>
    <h1>Checkout</h1>
    <h2>Order summary</h2>
    <ul>
      <li>Trail shoes — £89.50</li>
      <li>Delivery — £8.99</li>
    </ul>
    <form>
      <label for="card">Card number</label>
      <input id="card" autocomplete="cc-number" inputmode="numeric" required>
      <button id="pay" type="submit">Pay £98.49</button>
      <button type="button" id="use-saved">Use saved card</button>
    </form>
    <p id="status" role="status"></p>
  </main>
</body>
</html>

04. Step 2: locators that survive redesigns

Locators describe how to find an element. The resilient ones mirror how users think: the button called Pay £98.49, the field labelled Card number. Locators that encode page structure — CSS chains such as #root > div:nth-child(3) > button, or positional picks such as button.nth(4) — break on every redesign and hide ambiguity.

Playwright is strict by default, and the strictness is a feature. Watch what happens when a test uses a bare button locator while the page has two buttons:

TypeScript · e2e/brittle.spec.ts (a test to learn from, not to keep)
import { test } from '@playwright/test';

test('a bare locator matches two buttons and fails', async ({ page }) => {
  await page.goto('/');
  await page.locator('button').click();
});
Expected output (the failure you want to see)
Error: locator.click: Error: strict mode violation: locator('button')
resolved to 2 elements:
    1) <button id="pay" type="submit">Pay £98.49</button>
       aka getByRole('button', { name: 'Pay £' })
    2) <button type="button" id="use-saved">Use saved card</button>
       aka getByRole('button', { name: 'Use saved card' })

The failure names both buttons and even suggests the role-based alternatives. Writing the query as users perceive the page fixes it — getByRole('button', { name: 'Pay £98.49' }) — and that query keeps working when the layout around the button changes. A locator that can match two things should fail; a test that quietly clicks the wrong button is worse than a red build.

05. Step 3: the journey with web-first assertions

With resilient locators, the journey reads like the user story it is. Note what is absent: no sleeps, no waits for network idle, no manual retries. Actions auto-wait for an element to appear and become actionable, and web-first assertions such as toBeVisible() and toHaveText() retry until the condition holds or the timeout expires. The confirmation appears 300 ms after the click in this demo; the test neither knows nor cares:

TypeScript · e2e/checkout.spec.ts (journey)
import { test, expect } from '@playwright/test';

test('paying for an order shows the confirmation', async ({ page }) => {
  await page.goto('/');

  await expect(
    page.getByRole('heading', { name: 'Order summary' }),
  ).toBeVisible();
  await expect(page.getByRole('list')).toHaveText(/Trail shoes/);
  await expect(page.getByLabel('Card number')).toBeVisible();

  await page.getByLabel('Card number').fill('4242 4242 4242 4242');
  await page.getByRole('button', { name: 'Pay £98.49' }).click();

  await expect(page.getByRole('status')).toHaveText('Payment sent');
  await expect(
    page.getByRole('button', { name: 'Pay £98.49' }),
  ).toBeDisabled();
});

Two details earn their keep. getByLabel('Card number') proves the input is labelled — an unlabelled input breaks the test and real screen-reader users alike. And the last assertion checks the button became disabled, a visible state change shoppers rely on to avoid paying twice.

06. Step 4: an axe scan in the journey

The second test scans the page with axe-core, the same rule engine used in the accessibility audit lab. withTags limits the scan to rules mapped to WCAG 2.x levels A and AA. The scan runs against the live DOM at the moment analyze() fires, so anything the page script rendered is included:

TypeScript · e2e/checkout.spec.ts (accessibility gate)
import AxeBuilder from '@axe-core/playwright';

test('checkout page has no accessibility violations', async ({ page }) => {
  await page.goto('/');

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

  expect(results.violations).toEqual([]);
});
Expected output · npx playwright test e2e/checkout.spec.ts, both imports at the top of the file (timings omitted; they vary between runs)
Running 2 tests using 1 worker

  ✓  1 e2e/checkout.spec.ts:4:1 ›
       paying for an order shows the confirmation
  ✓  2 e2e/checkout.spec.ts:22:1 ›
       checkout page has no accessibility violations

  2 passed

An empty violations array turns the scan into a gate: any new automatable violation fails the test, and with it the build. It complements manual review, never replaces it — keyboard focus order and the meaning of announcements still need human judgement. Scan after key steps of a journey, not only on load, so states such as an open dialog get covered.

07. Fixtures keep journeys reliable

Two rules keep journeys reliable as the suite grows. First, setup belongs in fixtures: a fixture that signs in, seeds a basket or creates a fresh user runs before the test and cleans up after, so tests stay short and independent. Playwright can save a signed-in session once and reuse it through storageState, which keeps per-test sign-in cheap (its authentication guide shows the pattern).

Second, tests that run in parallel must not share mutable data. Two journeys editing the same seeded account pass alone and fail together; giving each test its own account — created in a fixture — removes the race instead of hiding it behind workers: 1.

08. The classics

09. Check your understanding

Practice check · 3 questions

Journeys, locators and gates

Three situations from an E2E suite.

Q1. What do web-first assertions such as toHaveText() remove from your tests?
Q2. Every journey signs in through the login form first, and that alone takes a third of the suite's run time. What does Playwright offer instead?
Q3. Where should the axe scan run inside a long checkout journey?
Practice only: not graded, not saved, not evidence.

10. Apply it

Take one critical journey from your product — sign-up, checkout, or the core workflow. Write it with role and label locators only, then deliberately break the page (rename a class, move a block) and confirm the journey still passes. Then fail something users would notice and confirm it fails. That contrast — robust to redesign, sensitive to regressions — is the property worth aiming at. The lab that follows assembles the full picture.

11. Review prompt

Without looking back: explain what trace: retain-on-failure records and when you would open it. Say why role and name locators survive redesigns while CSS chains do not, and what the strict mode error taught in this lesson was. Finally, name the two gates the journey suite applied and what each one fails on.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check