TestingVol. 11 · Part XI
0 / 0

Shelves / Testing

TS·118

End-to-End Testing

Testing whole user journeys through the real system: what E2E tests are for and how few you need, browser automation with Playwright (auto-waiting, locators, web-first assertions, fixtures, authentication state, network mocking, parallelism, trace viewer) versus Selenium/WebDriver BiDi and Cypress, API and system E2E tests, environment control, fixture setup and test data management, the anatomy and cure of flaky tests, when retries are acceptable, and debugging with traces, screenshots and videos.

29 topics · ~20 min read · 30-question quiz
Updated Suggest a correction

Start here: testing what the customer actually does

An end-to-end (E2E) test drives the real application the way a person does: open the page, choose a dish, set a quantity, click Place order, read the confirmation. It is the only kind of test that checks all the pieces working together in a real browser, and the most expensive kind to run and maintain. So you keep a small number of them, for the journeys that matter most, and you write them so they don't break for the wrong reasons.

Find elements the way a person does

The same journey written two ways, run against the page and against a redesign (new CSS classes and an extra wrapper div; same labels, same behaviour):

Python
# by CSS classes and structure
page.select_option("select.sel-1", label="Paneer Thali")
page.click("button.btn-primary")

# by what the user sees: labels, roles and names
page.get_by_label("Dish").select_option(label="Paneer Thali")
page.get_by_label("Quantity").fill("2")
page.get_by_role("button", name="Place order").click()
expect(page.get_by_role("status")).to_have_text(re.compile(r"Order #\d+ placed"))
Text
                       original page   redesign
CSS-selector test      PASSED          FAILED (Timeout waiting for "select.sel-1 option")
user-facing locators   PASSED          PASSED

Nothing the customer could see had changed, yet the CSS test broke. Locators based on labels and accessible roles break only when the experience changes, and they push you to keep the page accessible, since a button with no accessible name can't be found by get_by_role either.

Let the browser wait for you

expect(...).to_have_text(...) and actions like click() auto-wait: Playwright retries until the element is visible, enabled and stable, or a timeout passes. The confirmation here arrives about 0.2 s after the click, and no test contains a sleep. (Chapter 114 showed what fixed sleeps do: about one run in three failed.)

Test failure paths without breaking anything

To check what customers see when payment fails, the test intercepts the request in the browser:

Python
page.route("**/api/orders", lambda route: route.fulfill(status=502, body="bad gateway"))
Text
test_payment_failure_is_shown: PASSED   ("Sorry, payment failed. Please try again.")

No real payment provider had to fail. Network interception gives E2E tests deterministic control over slow, failing or unusual responses.

When a test fails, keep the evidence

A failing run recorded with tracing on produced an 18 KiB trace.zip with four screenshots, both network requests and the DOM snapshots before and after each action. Opening it (playwright show-trace trace.zip) shows exactly what the page looked like when the click timed out, which is far faster than re-running and guessing, especially for failures that only happen in CI.

How deep to go in end-to-end testing

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain what E2E tests are for and why to have few of them
L2 Write Playwright tests with user-facing locators, web-first assertions and isolated contexts
L3 Explain auto-waiting, fixtures, network interception, authentication state reuse and test data strategies
L4 Diagnose flaky and slow E2E suites using traces, and fix the causes
L5 Design an E2E strategy: which journeys, which environments, data seeding, parallelism and CI gates
L6 Run browser and device testing at scale with quality metrics across products

What E2E tests are for

End-to-end (E2E) tests exercise the system the way a user or external client does: through the real UI or public API, across the deployed services, databases, queues and third-party sandboxes. They answer: do the critical journeys actually work when everything is put together?

They are the most predictive tests and the most expensive: slow, sensitive to environment problems, harder to debug, and prone to flakiness. So:

  • Keep them few and focused on critical user journeys: sign up, log in, search, add to cart, checkout, payment, the core workflow your business depends on.
  • Don't use E2E tests to check edge cases and validation rules that unit, integration and contract tests cover more cheaply.
  • Treat failures as high-signal: a red E2E test should mean a real problem, which requires keeping them reliable.
Browser E2E API/system E2E
Drives Real browser via automation HTTP/gRPC/messages against a deployed system
Catches UI integration, front end ↔ back end, real user flows Service integration, configuration, deployment wiring
Speed Seconds per test Sub-second to seconds
Tools Playwright, Cypress, Selenium/WebDriver (BiDi), WebdriverIO REST Assured, Karate, Postman/Newman, Hurl, plain test frameworks + HTTP clients, k6 for functional checks
test runnerworkersfixtures browsercontextper test environment (ephemeral / pre-prod) front end services DB/queue payment sandbox seed data via API on failure: trace (DOM + network) · screenshot · video · HTML report
Anatomy of a browser E2E run. The test runner creates an isolated browser context per test, seeds data through APIs, drives the real front end, which calls the real back-end services and their data stores in a controlled environment; third-party providers are sandboxes or edge stubs. On failure, the run keeps a trace, screenshots and video for debugging.

Browser automation

The tools

  • Playwright (Microsoft): drives Chromium, Firefox and WebKit through their debugging protocols; test runner with fixtures, parallelism, auto-waiting, tracing; bindings for TypeScript/JavaScript, Python, Java and .NET. The default choice for new projects.
  • Cypress: runs inside the browser alongside the app; excellent interactive runner; historically limited to one tab/origin (improved over time); JavaScript only.
  • Selenium WebDriver: the W3C standard protocol, every language, every browser including real mobile via Appium; the newer WebDriver BiDi protocol adds event streams (console, network) and is being adopted across browsers and tools.

Playwright fundamentals

// tests/checkout.spec.ts — Playwright Test
import { test, expect } from "@playwright/test";

test("customer can buy a book", async ({ page }) => {
  await page.goto("/");
  await page.getByRole("searchbox", { name: "Search" }).fill("domain-driven design");
  await page.getByRole("button", { name: "Search" }).click();

  await page.getByRole("link", { name: /Domain-Driven Design/ }).first().click();
  await page.getByRole("button", { name: "Add to cart" }).click();
  await expect(page.getByTestId("cart-count")).toHaveText("1");     // web-first assertion, auto-retries

  await page.getByRole("link", { name: "Checkout" }).click();
  await page.getByLabel("Card number").fill("4242 4242 4242 4242"); // payment provider test card
  await page.getByRole("button", { name: "Pay" }).click();

  await expect(page.getByRole("heading", { name: "Thank you for your order" })).toBeVisible();
});

Key ideas:

  • Auto-waiting: actions like click() wait until the element is attached, visible, stable (not animating), enabled and receives events. No manual sleep.
  • Web-first assertions: expect(locator).toHaveText(...) retries until the condition holds or a timeout expires, matching how UIs update asynchronously. Avoid expect(await locator.textContent()).toBe(...), which checks once and races the UI.
  • Locators should reflect what users perceive, in this order of preference: role with accessible name (getByRole("button", { name: "Pay" })), label, placeholder, text, then test IDs (data-testid) for elements with no good accessible handle. Avoid CSS/XPath tied to layout (div > div:nth-child(3) > span). Role-based locators also nudge you toward accessible markup.
  • Isolation: each test gets a fresh browser context (like a new incognito profile: separate cookies and storage), cheap to create, so tests don't leak state.

Configuration, projects and parallelism

TypeScript
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  fullyParallel: true,
  forbidOnly: !!process.env.CI,               // fail CI if test.only was committed
  retries: process.env.CI ? 1 : 0,            // see "Retries" below
  workers: process.env.CI ? 4 : undefined,
  reporter: [["html"], ["junit", { outputFile: "results.xml" }]],
  use: {
    baseURL: process.env.BASE_URL ?? "http://localhost:3000",
    trace: "on-first-retry",                   // full trace when a test is retried
    screenshot: "only-on-failure",
    video: "retain-on-failure",
  },
  projects: [
    { name: "setup", testMatch: /auth\.setup\.ts/ },
    { name: "chromium", use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/user.json" }, dependencies: ["setup"] },
    { name: "webkit-mobile", use: { ...devices["iPhone 15"], storageState: "playwright/.auth/user.json" }, dependencies: ["setup"] },
  ],
  webServer: { command: "npm run start:test", url: "http://localhost:3000", reuseExistingServer: !process.env.CI },
});
  • Projects run the same tests on different browsers/devices; a setup project can run first (e.g. logging in).
  • Sharding splits a suite across CI machines (--shard=1/4), with reports merged afterwards.
  • webServer starts the app for local and CI runs.

Authentication state

Logging in through the UI in every test is slow and makes every test depend on the login page. Log in once (through the UI in a setup project, or via an API call), save the storage state (cookies, local storage), and reuse it:

TypeScript
// tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";
setup("authenticate", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill(process.env.E2E_USER!);
  await page.getByLabel("Password").fill(process.env.E2E_PASSWORD!);
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("button", { name: "Account" })).toBeVisible();
  await page.context().storageState({ path: "playwright/.auth/user.json" });
});

Keep one dedicated E2E test for the login flow itself (including MFA in a test-friendly way, such as TOTP secrets for test accounts).

Fixtures and page objects

Encapsulate repeated setup and page interactions:

  • Page Object Model: classes that expose user-level actions (cartPage.checkout()), hiding locators. Keeps tests readable and locator changes in one place. Don't let page objects contain assertions about business rules or become giant god-objects.
  • Playwright fixtures: typed, composable setup injected into tests (test.extend<{ cartPage: CartPage; seededUser: User }>) with automatic teardown, similar to pytest fixtures.
TypeScript
// fixtures.ts: a fixture that creates a user via API, and a page object
type Fixtures = { user: TestUser; cart: CartPage };
export const test = base.extend<Fixtures>({
  user: async ({ request }, use) => {
    const res = await request.post("/api/test/users", { data: { plan: "gold" } });   // test-only endpoint
    const user = await res.json();
    await use(user);
    await request.delete(`/api/test/users/${user.id}`);                             // cleanup
  },
  cart: async ({ page }, use) => { await use(new CartPage(page)); },
});

Network control

Playwright can intercept requests: stub third-party calls (analytics, maps, payment widgets you can't use in test), simulate errors and slow responses, or assert that a request was made:

TypeScript
test("shows a friendly error when search fails", async ({ page }) => {
  await page.route("**/api/search*", (route) => route.fulfill({ status: 503, body: "unavailable" }));
  await page.goto("/");
  await page.getByRole("button", { name: "Search" }).click();
  await expect(page.getByRole("alert")).toHaveText(/try again/i);
});

Mocking your own back end in browser tests turns them into front-end integration tests (useful, fast, but no longer end-to-end); be deliberate about which kind each test is.

Visual and accessibility checks

  • Visual comparison: await expect(page).toHaveScreenshot() compares against a baseline image with a tolerance; run in a consistent environment (same OS/fonts, usually a Docker image) to avoid false diffs; mask dynamic regions. Hosted alternatives: Chromatic, Percy, Applitools.
  • Accessibility: run axe-core in E2E tests (@axe-core/playwright) on key pages to catch missing labels, contrast problems and ARIA misuse.

API and system E2E tests

Not every E2E test needs a browser. API-level E2E tests drive the deployed system through its public interfaces and verify cross-service outcomes:

Java
// REST Assured: place an order, then poll until the async fulfilment pipeline marks it shipped
@Test
void orderFlowsThroughFulfilment() {
    String id = given().baseUri(baseUrl).auth().oauth2(token)
        .contentType(JSON).body(Map.of("sku", "book-1", "qty", 1))
        .when().post("/orders")
        .then().statusCode(201).extract().path("id");

    await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2)).untilAsserted(() ->
        given().baseUri(baseUrl).auth().oauth2(token).get("/orders/" + id)
            .then().statusCode(200).body("status", equalTo("SHIPPED")));
}
Text
# Hurl: plain-text HTTP E2E checks, good for smoke tests after deployment
POST {{base_url}}/orders
Authorization: Bearer {{token}}
{ "sku": "book-1", "qty": 1 }
HTTP 201
[Captures]
order_id: jsonpath "$.id"

GET {{base_url}}/orders/{{order_id}}
Authorization: Bearer {{token}}
HTTP 200
[Asserts]
jsonpath "$.status" matches "PLACED|PAID"

Smoke tests (a handful of fast E2E checks right after each deployment) and synthetic monitoring (the same journeys run continuously against production, e.g. with Playwright in Checkly, Grafana Synthetic Monitoring, Datadog Synthetics) extend E2E testing into production (Vol. 9 ch. 97).

Environment control

E2E results are only as reliable as the environment they run in:

  • Dedicated, reproducible environments: an ephemeral environment per PR or a stable pre-production environment deployed from the same artifacts and configuration as production (chapter 116; Vol. 6 ch. 84).
  • Known versions: record which version of each service was under test; E2E against a shared environment where other teams deploy at random is a classic source of mysterious failures.
  • Third-party dependencies: use provider sandboxes (Stripe test mode with test cards), or stub them at the edge with WireMock/MockServer where sandboxes are unreliable.
  • Time, feature flags and configuration: pin feature flag states for tests (or test both states explicitly); control time-dependent behaviour (test hooks to set a clock in non-production builds).
  • Health checks before starting: wait until all services report ready rather than failing the first tests.

Test data

Test data is the hardest part of E2E testing.

Approach How Notes
Create per test via API Fixtures call public or test-only APIs to create users, products, orders Most isolated and parallel-safe; needs those endpoints (disabled in production)
Seed a known baseline Load a dataset at environment creation (SQL dumps, seed scripts) Fast; shared data must be read-only for tests, or tests interfere
Unique identifiers Each test uses unique emails/names (e2e+${uuid}@example.com) Avoids collisions when running in parallel
Synthetic data generation Faker/Datafaker/Bogus generate realistic data Never copy production personal data into test environments without anonymisation
Cleanup Delete what you created, or rely on the environment being ephemeral TTL-based cleanup jobs for long-lived environments

Rules: tests create what they need and never rely on data created by other tests; avoid depending on shared mutable records ("the test user's cart must be empty"); make test-only endpoints impossible to enable in production.

Flaky tests

Why tests flake

A flaky test passes and fails on the same code. Common root causes:

Cause Example Fix
Race with async UI Clicking before the button is enabled; reading text before it updates Auto-waiting actions, web-first assertions; never fixed sleeps
Test interdependence Test B relies on data or state from test A; order changes Isolated contexts and data per test
Shared environment Another team deployed; someone changed shared data Ephemeral/dedicated environments, version pinning
Time Tests around midnight, DST, time zones, expiry Controlled clocks, explicit time zones
Animations and timing Element moving during click Disable animations in test mode; Playwright waits for stability
Third-party services Sandbox outage, rate limits Stub at the boundary or tolerate with clear diagnostics
Resource limits CI runners overloaded; timeouts too tight Adequate resources, realistic timeouts, fewer workers
Non-deterministic data Search ranking ties, unordered lists Assert on contents, not position; sort
Real bugs Race conditions in the app itself Investigate! Flaky tests sometimes reveal genuine concurrency bugs

Managing flakiness

  • Measure: track pass/fail history per test; flag tests that fail and then pass on retry without code changes (most CI systems and test analytics tools such as Buildkite Test Engine, Datadog Test Optimization, Trunk, Currents for Playwright do this).
  • Quarantine: move a flaky test out of the blocking suite (still running, results visible) with an owner and a deadline, so it doesn't train everyone to ignore red builds.
  • Fix root causes using traces; delete tests whose value doesn't justify their cost.
  • Stress-test new E2E tests before merging (--repeat-each=20) to catch flakiness early.

Retries

Retries are a mitigation, not a fix:

  • Acceptable: a single automatic retry in CI for E2E tests that depend on real networks and browsers, as long as retried-then-passed tests are reported as flaky and tracked (Playwright marks them "flaky" in its report).
  • Harmful: unlimited or silent retries that hide real intermittent bugs (a race condition customers also hit), and retries at the wrong level (retrying an entire suite).
  • Never retry unit tests: flakiness there is always a determinism bug.

Debugging with traces, screenshots and videos

When an E2E test fails in CI, you need to see what happened without re-running it locally:

  • Playwright Trace Viewer: a trace (trace.zip) records every action with DOM snapshots before/after, screenshots, console logs, network requests and responses, and source locations. Open with npx playwright show-trace trace.zip or trace.playwright.dev. Configure trace: "on-first-retry" or "retain-on-failure" to capture it only when useful.
  • Screenshots on failure and videos (retain on failure) show the visual state.
  • UI mode (npx playwright test --ui) for local time-travel debugging, watch mode and locator picking; --debug steps through with the inspector; codegen records interactions into a starting script.
  • Correlate with back-end observability: propagate a trace header or test ID from the test so back-end logs and distributed traces for that run can be found (Vol. 9 ch. 101).
  • Upload artifacts (HTML report, traces, videos) from CI and link them in the failure summary.

Lab: end-to-end tests that survive change

Playwright 1.63 for Python (sync API) with headless Chromium, pytest 9.1 and pytest-xdist, on the lab machine (2 CPU cores). The app is a one-page order form served by Python, with a /api/menu endpoint (100 ms) and /api/orders (200 ms). A pytest fixture runs every test against two variants: the original page and a redesign with different classes and an extra wrapper.

Experiment 1: locator strategy versus a redesign

Text
PASSED test_order_css_selectors[a]
FAILED test_order_css_selectors[b]   Page.wait_for_selector: Timeout 3000ms exceeded.
                                       - waiting for locator("select.sel-1 option")
PASSED test_order_user_facing_locators[a]
PASSED test_order_user_facing_locators[b]
PASSED test_payment_failure_is_shown[a]
PASSED test_payment_failure_is_shown[b]
1 failed, 5 passed in 7.16s
call durations: user-facing 0.55–0.58 s; failed CSS test 3.04 s (its timeout)

A second lesson from building it: the first version of the CSS test waited for select.sel-1 option to be visible, and timed out after 30 s even on the original page, because <option> elements inside a closed <select> are never visible. It needed state="attached". Hand-written waits make you know such details; get_by_label("Dish").select_option(...) handled it automatically. Playwright's recommended order of locators is role, label, placeholder, text, alt text and title, then data-testid for elements with no user-facing handle, and CSS or XPath last.

Experiment 2: network interception

Python
page.route("**/api/orders", lambda route: route.fulfill(status=502, body="bad gateway"))
Text
PASSED test_payment_failure_is_shown[a]   status text: "Sorry, payment failed. Please try again."

Use interception for states that are hard to produce on demand (provider outages, slow responses with route.continue_ after a delay, empty lists, very long names), and for third-party scripts you don't want in tests at all. Don't intercept your own backend in the critical-journey tests, or they stop being end-to-end; keep a small set of fully real journeys and use interception around them.

Experiment 3: traces as evidence

Text
test failed: TimeoutError Page.click: Timeout 2000ms exceeded.
trace.zip 18 KiB, 9 entries: network, resources, screencast, stacks, trace
  network requests recorded: 2
  screenshots: 4

In pytest-playwright, --tracing retain-on-failure keeps traces only for failing tests, so CI artefacts stay small; --video retain-on-failure and --screenshot only-on-failure work the same way.

Experiment 4: parallelism on a 2-core machine

24 journeys, each in its own browser context:

Text
workers=0 (serial): 24 passed in 12.46s
workers=2:          24 passed in  8.78s
workers=4:          24 passed in 10.05s
workers=8:          24 passed in 17.05s

Two workers matched the two cores and gave a 1.4× speed-up; beyond that each worker launched its own Chromium and they fought for CPU, so 8 workers were slower than none. Size parallelism to the machine (CI runners included), and remember that parallel tests need independent data: each journey here placed its own order, so they couldn't collide. For bigger suites, sharding across several CI machines (--shard=1/4 in Playwright Test) scales further than workers on one.

Try it yourself

  1. Add a data-testid to the menu list and write a test that checks the two dishes appear. When is a test ID better than a role?
  2. Log in once in a setup step, save storage_state to a file, and reuse it in every test. Measure the time saved.
  3. Use page.route to delay /api/menu by 3 s and check the page shows a loading state, not an empty select.
  4. Run the suite under --browser firefox --browser webkit and see whether anything differs.

Revision sheet: end-to-end testing

Key ideas

  • Purpose: verify a few critical journeys through the assembled system as a user would; the rest belongs lower in the stack.
  • Playwright: auto-waiting actions, web-first assertions (expect), isolated browser contexts, fixtures, network interception, tracing, codegen, multi-browser (Chromium, Firefox, WebKit).
  • Locators: role, label, text first; data-testid when nothing user-facing exists; avoid CSS/XPath tied to structure.
  • Determinism: no sleeps; own your test data (create it per test or seed it); isolate contexts; control time and third parties.
  • Speed: reuse authentication state, parallelise to the hardware, shard across machines, run the smallest critical set on every change and the rest nightly.
  • Evidence: traces, videos and screenshots retained on failure.
  • Beyond functional: accessibility checks (axe), visual comparisons, cross-browser runs.

Numbers to remember

  • Lab: about 0.55 s per journey locally; a redesign broke the CSS test and not the user-facing one.
  • Lab: 2 workers on 2 cores gave 1.4×; 8 workers were 1.4× slower than serial.
  • Lab: a failing run's trace was 18 KiB with 4 screenshots and 2 network requests.

Pitfalls

  • Hundreds of E2E tests as the main safety net.
  • Fixed sleeps; CSS selectors tied to styling.
  • Tests sharing accounts or data, failing when run in parallel.
  • Logging in through the UI in every test.
  • Mocking your own backend in "end-to-end" tests.
  • Retrying failures without reading traces.

Glossary

  • Browser context: an isolated session (cookies, storage) inside one browser.
  • Web-first assertion: an assertion that retries until it passes or times out.
  • Storage state: saved cookies and local storage used to skip login.
  • Sharding: splitting a suite across machines.
  • Trace viewer: Playwright's tool for replaying a recorded run.