Skip to content

    Frontend System Design

    End-to-End Testing and Flaky Tests

    Use a few end-to-end tests for the journeys that must work and keep them trustworthy: auto-waiting, isolation, retries as a signal, traces and a flake policy.

    By Published 13 min read

    • frontend-system-design
    • testing
    • end-to-end
    • flaky-tests
    • playwright
    Share

    Standard lessonintermediateFrontend System Design

    Before this: The Testing Pyramid and Trophy for Front Ends

    What you'll learn: By the end of this lesson you will be able to say what an end-to-end test is for and which journeys deserve one, explain why these tests flake and name the usual causes, write a test that waits for a condition instead of a clock, keep tests isolated, use retries and traces as signals rather than cures, set a policy for a flaky test, and read a Playwright configuration, all without running a browser here.

    Honesty note. Browser automation is not run on the machine this course is written on, so nothing here was run in a browser. The Playwright configuration and test code below are shown, not run: they follow the documentation pages listed at the end, and should be run in CI or on your own machine before you trust them. The only numbers computed here are plain arithmetic.

    Think of a smoke detector. It is valuable only if it rings when there is a fire, and stays quiet otherwise. A detector that rings at toast gets its battery pulled, and then it is worse than none. An end-to-end test suite is a smoke detector for your whole product: a real browser, the real app, a user's path. Its value is not how many tests it has, but how much you believe it when it goes red.

    The running example is the checkout journey of a grocery marketplace, the front end of the ShopStream marketplace used in this course: search for a product, add it to the basket, pay, see the confirmation.

    The core idea

    1. End-to-end (E2E) tests check a whole journey through the real UI. They are the only tests that run the browser, the built app and the wiring together, so they find problems no smaller test can.
    2. They are slow, broad and easy to make unreliable. Many moving parts means many chances for timing and state to differ between runs. So you write few of them, for the paths that must not break.
    3. A flaky test is one that gives different results on the same code. It destroys trust. The cure is to remove the cause (usually a hidden wait or shared state), not to retry until green.

    What an E2E test is for

    The pyramid (or trophy) lesson in this module argues for many fast tests and few slow ones; E2E sits at the narrow top. A good E2E test covers a critical journey (sign in, search, pay: the ones you would be paged for), asserts what a user would see, and leaves details to cheaper tests. Playwright's best-practices page puts the aim in one sentence: automated tests should verify that the application code works for the end users, so they should use what the user sees, not implementation details.

    Question Better at
    Does the formatter round correctly? A unit test
    Does the screen show the right state when the API fails? An integration test with a mocked network (lesson)
    Can a shopper log in, pay and see a confirmation? An end-to-end test

    Why they flake

    An E2E test is a conversation between a script and an application that run at different speeds. The script asks "is the button there yet?" and the app answers when it is ready. Most flakes are one of five things.

    Cause What happens Fix in one line
    A race: the test acts before the page is ready Click on a button that is not enabled yet Wait for a condition, not a time
    Shared state: tests depend on each other or on leftover data Passes alone, fails in a suite, or after another test Each test sets up its own state
    Uncontrolled inputs: real clock, random data, a live third party Output changes between runs Control or mock what you do not own
    Environment: a loaded CI machine, a cold server, animations Slower than the author's laptop Make waits conditional; run few workers
    A real bug that only shows sometimes The test is right and the app is wrong Treat it as a bug, not noise

    The last row matters: sometimes the flake is the product failing intermittently, and retrying hides a race your users will hit.

    Figure 1. Why the same test can pass and fail

    sequenceDiagram accTitle: A race between a test and the app accDescr: Two runs of the same test. In the fast run the app has rendered the Pay button enabled when the test clicks, so the test passes. In the slow run the app is still loading, the test clicks a disabled button too early or after a fixed sleep that was too short, and the test fails. A waiting assertion would pass in both runs. participant T as Test participant A as App Note over T,A: Run 1 (fast machine) A->>A: Pay button enabled at 300 ms T->>A: click at 500 ms (fixed sleep) A-->>T: ok Note over T,A: Run 2 (loaded CI machine) T->>A: click at 500 ms (same sleep) A->>A: Pay button enabled at 900 ms A-->>T: fails: button not ready

    How to read this: nothing about the code changed between the runs, only the speed. The fixed 500 ms sleep is a guess about the machine. The numbers are illustrative.

    Wait for a condition, not a clock

    Playwright's answer to the race has two parts, both from its documentation.

    Actionability checks. Before an action such as a click, Playwright waits until the element is visible, stable (the same bounding box for at least two consecutive animation frames), able to receive events at the action point (nothing covers it), and enabled. If the checks do not pass within the timeout, the action fails with a TimeoutError.

    Web-first assertions. Matchers like toBeVisible and toHaveText retry until the condition holds or the assertion timeout (5 seconds by default) is reached. The documentation also warns that non-retrying assertions check a value once and, because pages show information asynchronously, can lead to a flaky test. For checks with no built-in matcher it offers expect.poll and expect.toPass.

    Locators carry the same behaviour: Playwright calls them the central piece of its auto-waiting and retry-ability, and recommends role locators as the closest way to how users and assistive technology perceive the page. Locators are also strict: an operation that targets one element throws if more than one matches, so an ambiguous selector fails loudly.

    Illustration 1: the minimal example

    The same check twice. The first reads the page once, the second waits for it. This code was not run here.

    // flaky: reads once, right after the click
    await page.getByRole("button", { name: "Pay" }).click();
    const text = await page.getByRole("status").textContent();
    expect(text).toBe("Order confirmed");
    
    // steadier: the assertion retries until the text appears or the timeout passes
    await page.getByRole("button", { name: "Pay" }).click();
    await expect(page.getByRole("status")).toHaveText("Order confirmed");

    The first version races the server. The second states the condition and lets the tool wait for it.

    Isolation: every test builds its own world

    The best-practices page says each test should be completely isolated from another and run independently, so a failure does not cascade. Playwright helps: it runs tests in parallel across worker processes, tests in one file run in order in the same worker, workers cannot talk to each other, and after any test failure the worker is shut down so the next test starts from a clean environment. The same page advises against serial mode: if one serial test fails, all later ones are skipped.

    What you must supply is data isolation. A test that depends on "the order from the previous test" or on a shared account's basket will pass or fail by order and by who else is running. Give each test its own user or its own records, created by an API call or a seed step rather than by clicking through the UI. Mock what you do not own: the same page says to test only what you control and to use the Playwright network API to guarantee a response. In the checkout example the payment provider's sandbox is slow and rate-limited, so the test fulfils the payment call itself.

    Illustration 2: the realistic example

    A checkout test with its own data and a controlled payment response (not run here; the route and fulfill call follow the documentation's mocking example).

    import { test, expect } from "@playwright/test";
    
    test("a shopper can pay for a basket", async ({ page }) => {
      // third party we do not own: answer it ourselves
      await page.route("**/api/payments", async (route) => {
        await route.fulfill({ json: { status: "approved", reference: "test-ref-1" } });
      });
    
      await page.goto("/products/oat-milk");
      await page.getByRole("button", { name: "Add to basket" }).click();
      await page.getByRole("link", { name: "Basket" }).click();
      await page.getByRole("button", { name: "Pay" }).click();
    
      await expect(page.getByRole("heading", { name: "Order confirmed" })).toBeVisible();
    });

    Notice what it does not do: no sleep, no CSS selector, no dependency on another test, no live payment provider. It is one journey with one assertion at the end, and leaves rules such as price rounding to cheaper tests.

    Figure 2. Isolated tests, controlled edges

    An end-to-end test with its own data and a stubbed third partyTest to Browser (drives); Browser to App and API (requests); Browser to Payment provider (route fulfils)REAL, OWNEDTest: one journeyTestone journeyBrowser: realBrowserrealApp and API: built, seededApp and APIbuilt, seededPayment provider: stubbed in testPaymentproviderstubbed in testdrivesrequestsroute fulfils

    How to read this: the accent boxes are what the team owns and tests for real. The muted box is a third party the test answers on its own, so its mood cannot fail your build.

    Retries are a signal, not a cure

    Playwright can retry a failed test. Retries are off by default. When one test fails, the worker process and its browser are discarded and a new worker runs the retry. A test that fails the first time but passes on retry is reported as flaky. In the documentation's wording: passed means passed first time, flaky means failed first and passed on retry, failed means failed all retries.

    That status is the useful part. A retry hides a flake from the build, but the report still names it. Use retries so a suite is not red for one bad run, and use the flaky list as a queue of work. If a test spuriously fails 2% of the time (illustrative), one retry makes a spurious red about 0.04% (0.02 squared), but the cause stays. And flake rates compound across tests.

    A run of that arithmetic in Node 26.13.1, with the rates and test counts chosen for illustration:

    tests=50 spurious-failure-rate=0.001 P(all green)=0.951
    tests=50 spurious-failure-rate=0.005 P(all green)=0.778
    tests=50 spurious-failure-rate=0.02 P(all green)=0.364
    tests=200 spurious-failure-rate=0.001 P(all green)=0.819
    tests=200 spurious-failure-rate=0.005 P(all green)=0.367
    tests=200 spurious-failure-rate=0.02 P(all green)=0.018
    p=0.02 retries=0 P(test still red)=2.0e-2
    p=0.02 retries=1 P(test still red)=4.0e-4
    p=0.02 retries=2 P(test still red)=8.0e-6

    The first six lines are (1 - p)^n: the chance that n independent tests, each failing spuriously with probability p, are all green on one run. A suite of 200 tests with a 0.5% flake rate each is green on about 37% of runs, which is how a team learns to ignore red. The last three lines are p^(retries+1): retries cut the chance that one flaky test stays red, at the cost of hiding it. These figures assume independence and illustrative rates; real flakes are rarely independent.

    Illustration 3: the failure, a test that depends on order

    A test "can see its order in history" passes after "can pay for a basket" in the same worker and fails alone, because it assumed the order already existed. On a laptop running files in order it never failed; on CI with parallel workers the order changed, and a retry on a fresh worker passed by luck. The fix is for the test to create its own order through a seed call, not another retry.

    Figure 3. What to do with a flaky test

    flowchart TD accTitle: Triage for a flaky end-to-end test accDescr: A test is reported flaky, meaning it failed and then passed on retry. First open the trace of the failed attempt. If the trace shows the test acted before the page was ready, replace the wait with a condition. If it shows shared or leftover state, give the test its own data. If it shows a real intermittent app failure, file a product bug. If the cause is not found within a set time, quarantine the test with an owner and a deadline. F["Test reported flaky
    (failed, then passed on retry)"] --> T["Open the trace
    of the failed attempt"] T --> Q{"What does it show?"} Q -->|"acted too early"| W["Wait for a condition
    (locator, web-first assertion)"] Q -->|"shared or leftover data"| I["Give the test its own data"] Q -->|"the app really failed"| B["File a product bug"] Q -->|"cause unclear"| X["Quarantine with an owner
    and a deadline"]

    How to read this: every branch ends in a change that removes a cause. Quarantine is the last branch and has a deadline, so "temporarily skipped" does not become "deleted by neglect".

    Traces: see what happened

    Debugging a failure you cannot reproduce needs a record. Playwright's documentation recommends its trace viewer for CI failures instead of videos and screenshots: a trace shows a timeline, DOM snapshots and network requests, and lets you step through each action and look at the page before and after it. The default setup records a trace on-first-retry, meaning on the first retry of a failed test, which is exactly the flaky case.

    The configuration (shown, not run)

    A configuration following the documentation's own example, with the lines that matter for flakiness marked. It was not run here.

    import { defineConfig, devices } from "@playwright/test";
    
    export default defineConfig({
      testDir: "tests",
      fullyParallel: true,                       // tests in all files run in parallel: they must be isolated
      forbidOnly: !!process.env.CI,              // fail the build if test.only was committed
      retries: process.env.CI ? 2 : 0,           // retry on CI only; flaky tests are listed in the report
      workers: process.env.CI ? 1 : undefined,   // fewer workers on a small CI machine
      reporter: "html",
      use: {
        baseURL: "http://localhost:3000",
        trace: "on-first-retry",                 // record a trace when a failed test is retried
      },
      projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
      webServer: {
        command: "npm run start",                // start the app before the tests
        url: "http://localhost:3000",
        reuseExistingServer: !process.env.CI,
      },
    });

    A test can detect a retry at runtime with testInfo.retry, and retries can be set for one group with test.describe.configure({ retries: 2 }).

    Build it

    This lesson has no lab. End-to-end tests need a real browser and no browser automation is run here; the Playwright code above is for CI or your own machine. The only thing run was the arithmetic above, in Node. The network-mocking lab (examples/frontend/labs/network-mocking) is the cheaper place to test most failure behaviour.

    Trade-offs

    Choice Gain Cost
    Few E2E tests, critical journeys only Fast, trusted suite Less breadth; rely on lower layers
    Many E2E tests Wide coverage Slow, flaky, expensive to maintain
    Retries on CI A bad run does not block merges Can hide real flakes if nobody reads the report
    Mock third parties Stable, fast The mock can drift from the real service
    Fully parallel Short run time Tests must be fully isolated

    In practice: a suite nobody believes

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The marketplace has about 200 E2E tests (illustrative) and a nightly run that is red most mornings. Engineers re-run until it passes and merge. A real checkout bug reached production behind a week of red runs everyone assumed were flakes.

    Starting architecture

    Figure 4. The suite the team has

    Starting architecture: many tests sharing one environment200 E2E tests to Shared staging (reads, writes); Shared staging to Live sandbox (real calls)200 E2E tests: ordered, shared200 E2E testsordered, sharedShared staging: one databaseShared stagingone databaseLive sandbox: third partyLive sandboxthird partyreads, writesreal calls

    How to read this: the warning boxes are the sources of flakes: tests that share data and an environment whose third party is outside the team's control.

    Options considered

    Option What it fixes What it costs Risk
    Raise retries to 5 Fewer red runs Hides flakes and real bugs The suite stops being believed
    Delete the flaky tests A green suite Lost coverage The bug classes return
    Cut to critical journeys, isolate data, stub the third party, track flakes A smaller, trusted suite A rewrite and a policy Time spent now

    The decision

    Field Decision record
    Context A red run no longer means anything, and a real bug was missed behind assumed flakes.
    Decision Keep about a dozen critical journeys as E2E. Move the rest to integration tests with a mocked network. Seed data per test, stub the payment provider, retries 2 on CI, trace on first retry, and read the flaky list weekly.
    Consequences, good A red run is a reason to stop; failures come with a trace.
    Consequences, bad Less E2E breadth; a stubbed payment path that is not the real one.
    Revisit when The flaky list stays empty for a quarter, or an incident shows the stub hid a real fault.

    Rollout and verification

    1. List the journeys whose failure you would be paged for, and cut the rest.
    2. Fix the top flakes first, using traces, one cause at a time.
    3. Add a policy: a flaky test gets an owner and a deadline, then is quarantined, not left red.
    4. Review the flaky report weekly.

    The 2 a.m. failure

    The payment stub keeps answering "approved", while the real provider changed its response a week ago and checkout fails for real shoppers. The suite is green.

    First three checks: (1) compare one real payment response with the stub; (2) look for provider changes in its changelog; (3) check whether a contract or smoke check runs against the real provider. Mitigation: roll back or patch the client, and update the stub. Follow-up: a small scheduled check against the real sandbox, outside the merge path, so a stub cannot hide drift forever.

    Architect's notes

    • Few tests, high value. Count the journeys you would be paged for and stop near there.
    • Trust is the product. One flake you ignore teaches people to ignore them all.
    • Read the flaky report. It is a free list of the weakest tests.
    • Keep a real-world check somewhere. Stubs keep builds stable; something else must notice when the real service moves.

    Common mistakes

    • Fixed sleeps as the fix for every timing problem.
    • Tests that depend on order or on data another test left behind.
    • Raising retries instead of finding the cause, until red means nothing.
    • Selecting by CSS class or position instead of by role and name.
    • Quarantining without a deadline, so skipped tests rot.
    • Assuming every flake is test noise, and missing a product bug.

    Key takeaways

    • E2E tests protect a few critical journeys; they are slow and broad by nature.
    • Most flakes are races, shared state, uncontrolled inputs or a loaded environment, and some are real bugs.
    • Wait for a condition (auto-waiting, web-first assertions), never for a clock.
    • Isolate every test and stub what you do not own.
    • A retry is a signal: the flaky status is the useful output.
    • Record traces on the first retry and give every flake an owner and a deadline.

    Practice exercises

    Exercise 1: Starter (30 min). Take a test of your own that uses a fixed sleep. Replace it with an assertion that waits for a condition and say what it now depends on.

    Exercise 2: Intermediate (2 hours). Compute, for your own suite size and an observed flake rate, the chance of an all-green run with (1 - p)^n, then say what that tells you about how often people see red.

    Exercise 3: Advanced (half day). Write the policy for a flaky test: who is told, the deadline, what quarantine means and what evidence restores it. Apply it on paper to three past flakes.

    In this course:

    Also in this module, in plain text because they are written in the same round: The Testing Pyramid and Trophy, Unit and Component Testing, Contract Testing for Front Ends and Visual Regression Testing.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments