End-to-end and browser tests
The one test that drives the real page, the real API and the real database together: what it proves, why it flakes, and how to write the few you keep
The checkout page fills its product list from GET /products after it loads. A browser test opens the page, sleeps for 0.5 s, types a quantity, clicks Place order and checks the result. It passes every time on Nokuthula's laptop, where /products answers in 20 ms. On the CI machine /products takes 1 s on a bad run. What does the test report on that run?
A browser test, also called an end-to-end test (E2E), drives a real browser against the running system. It opens a page, clicks and types as a person would, and checks what appears on the screen. Everything in the chain is real: the page’s JavaScript, the HTTP calls, the API, the database. Only the far edge is faked, and for Ojaline that edge is the payment provider.
This chapter teaches how to write one that you can trust, and how to decide that you need only a few.
What a browser test is for
Every other test in this module stops short of something. A unit test never starts the server. An integration test with a real database never runs a browser. An API test sends requests that you wrote, not the ones the page’s own script builds. The Friday failure in the Why lives in the gap: the script and the endpoint were each fine, and the join between them was broken.
A browser test closes the join. In the lab it proves one chain, from fetch("/products") in the page, through POST /orders with an Idempotency-Key header, through the pricing, stock and provider call, to the sentence Order ord_... placed on the screen. If any link breaks, the test breaks.
It does not prove the rules inside the links. Whether ₦24,000 of fabric earns the 5% tier discount is a pricing rule. You check it with a unit test in a few milliseconds, with the boundary values from earlier in the course, and a browser test of the same rule takes a hundred times longer and fails for a hundred more reasons.
The cost side
The price of a browser test is four things.
- Time. Starting a browser and two servers costs about a second. In the lab, one happy-path journey runs in about 0.12 s once everything is up. A page-level API test of the same endpoints runs in about 0.01 s. A suite of 400 browser tests is a 10-minute suite, and a suite of 400 unit tests is a 1-second suite.
- Flakiness. More moving parts means more timing. A browser, a page script, a network and a server all run on their own schedules, and the test has to wait for the right moment in each.
- Diagnosis. When a unit test fails, the failing line is a few lines from the cause. When a browser test fails, the cause is anywhere in four layers, and the message is
Timeout 5000ms exceeded. - Maintenance. The page changes for reasons that have nothing to do with correctness: a label is reworded, a button moves. Every test that depends on the old shape breaks together.
Martin Fowler’s note on the test pyramid, in the reading list, states the consequence: write many fast tests and few slow ones, and keep the pyramid shape. Mike Wacker’s 2015 post on the Google Testing Blog, also in the reading list, makes the same case from Google’s side: end-to-end tests are slow, flaky and hard to debug, so keep a small set of broad flows and let unit tests carry the rest. His note on the broad-stack test names this kind of test and adds a rule for the edge: replace remote systems with test doubles that a contract test keeps honest. The lab already follows that rule, since the checkout page talks to the fake provider and never to a real payment service. The next chapter in the module, The shape of a suite, builds on these arguments.
The result is a short list of journeys. For Ojaline’s checkout it is one: add to cart, pay, see the confirmation, and one unhappy variant, the declined card. Everything else belongs lower down.
Playwright in four ideas
The lab uses Playwright for Python, version 1.60.0 in requirements.txt. Playwright controls a real Chromium. These four ideas carry most of what you need.
A browser, a context and a page. You launch one browser, which is the expensive part. Each test gets a fresh browser context, which is like a private window with its own cookies and storage and costs a few milliseconds. A context holds pages. Isolation is the property that stops one test’s leftovers from changing another’s result, and a context per test gives it to you for almost nothing. The Playwright best-practices page states the rule directly: each test should be completely isolated from another.
Locators. A locator describes how to find an element. It does not hold the element; it looks again each time you use it. Prefer the ones that match what a user sees:
| Locator | Finds | In the checkout page |
|---|---|---|
page.get_by_role("button", name="Place order") |
an element by its accessibility role and visible name | the button |
page.get_by_label("Quantity") |
a form field by its label text | the number input |
page.get_by_role("status") |
an element with role="status" |
the result paragraph |
page.get_by_text("Order") |
an element by its text | any message |
page.locator("#place") |
a CSS selector | the button, by its id |
The CSS id still works, and it is the last choice. It is invisible to the user and changes when a developer cleans up. A role and a name are what a screen reader announces, so a test that finds the button this way also checks that a person using assistive technology could find it. A test id (data-testid, found with get_by_test_id) is the fallback when the page offers no role or label.
Auto-waiting. Before it acts, Playwright runs actionability checks and retries until they pass or the timeout ends. A click waits for the element to be visible, stable (not moving), able to receive events and enabled. A select_option waits for the element to be visible and enabled, and also for the option you named to exist. That second wait is the cure for the Predict question: select_option(label="Shea butter, 500 g (3500 NGN)") does not return until the product list has loaded. Nothing in your test says how long that takes.
Web-first assertions. An ordinary assert checks once. expect(locator).to_have_text(...) and its relatives retry until the condition holds or the deadline passes. They are the tool for the second half of a test, where you wait for the page to reach a state:
from playwright.sync_api import expect
expect(page.get_by_role("status")).to_contain_text("placed") # retries for up to 5 s
assert "placed" in page.get_by_role("status").inner_text() # reads once, right now
The second line is the flaky one. It reads the text at the moment it runs. If the order is still in flight, it reads an empty string. Use expect for anything the page changes by itself, and read once with inner_text only when you have already waited by other means.
The wait is the whole game
Most flaky browser tests are one mistake: a test that asserts before the system has finished. The cure is to tell the test what to wait for, not for how long.
test('job finishes', () => {
startJob();
sleep(100); // a guess about how long the job takes
expect(job.isDone()).toBe(true);
});test('job finishes', async () => {
startJob();
await waitFor(() => job.isDone(), { timeout: 5000 }); // the real condition, with a deadline
expect(job.result()).toBe('ok');
}); In the simulation, watch the two sleep runs side by side. On a quiet machine the 100 ms sleep is long enough, and on a loaded one the same sleep is shorter than the job. The code under test is identical in both runs, and the verdict flips with the load. Then run the fix: poll for the real condition with a deadline. The slow run now passes, and the job that never finishes fails fast with a clear message. A browser test has the same shape, with the page in place of the job, and Playwright’s auto-waiting and expect are the polling with a deadline built in. The lesson on this race goes through the mechanism, and the chapter Flaky tests in this module treats the whole family.
Three rules follow, and the lab applies each.
- Never
time.sleep. Every sleep is a guess, and the guess costs time on every run, even when it is right. - Wait for something the user would wait for. An element to appear, a text to change, a request to finish. If you cannot name it, the page may not be telling the user either, which is a defect worth reporting.
- Keep one deadline for everything. The lab sets
context.set_default_timeout(5_000), which is 5 s for every wait. A deadline in milliseconds, set in one place, turns a hang into a red test with a message.
Make the slow thing slow on purpose
You cannot prove a test is robust by running it on a fast machine. You can make the slow thing slow. Playwright can intercept a request and hold it back, with page.route. Delay /products by 2 s and a test that only works because the catalogue is quick will fail every time, not one run in six. A flaky test becomes a deterministic one, and you can fix it and watch it stay fixed.
The same idea covers the unhappy path. The fake payment provider has modes (ok, decline, slow, 500, timeout), set with POST /_admin/mode. Setting decline makes the declined card happen on demand, with no real card and no hope that a sandbox misbehaves at the right moment. The browser test drives the page to the declined state and checks the message. Whatever the test sets, it puts back (the lab does this with a fixture that calls POST /_admin/reset), because a test that leaves the provider in decline breaks every test after it.
When it fails, keep the trace
A browser test fails on a CI machine you cannot sit at. A screenshot helps a little. A trace helps much more.
A trace is a zip file that records each Playwright action with a DOM snapshot before and after it, a film strip of screenshots, every network request with its response, the console messages and the lines of your test that ran. You start it per context and save it only if the test fails:
context.tracing.start(screenshots=True, snapshots=True, sources=True)
...
context.tracing.stop(path="traces/test_naive_buy.zip") # on failure only
You open it with playwright show-trace traces/test_naive_buy.zip, or by dropping the file onto trace.playwright.dev in a browser. The viewer lists the actions on the left. Click one and the page appears as it stood at that moment, with the network and console tabs beside it. In the lab’s failing test you will see the click, then the response to POST /orders with unknown_product, then the screenshot showing Failed: unknown_product. It tells you in ten seconds what a message of assert 'placed' in 'Failed: unknown_product' only hints at.
Saving every trace is wasteful, since a trace is about 130 KB and a green test has nothing to show. The lab’s conftest.py saves one only on failure and a CI job can upload the traces/ folder as an artefact. The chapter Flaky tests and a later chapter on CI at scale return to the habit.
Keeping the journey small
Four habits keep a browser suite from growing into the problem it was meant to solve.
- One journey per test, and each journey is one a user cares about. The happy path for buying, and the one failure whose message matters.
- Go in through the front door, check at the back. The test drives the page, then asks the API for the saved order (
page.request.get("/orders/...")) to check what was stored. That is one assertion on persisted state, which is cheaper and stronger than reading more text off the screen. - Do not log in or build data through the page when an API call will do. If a journey needs a product to exist, create it with
POST /productsfirst. The page is the thing under test, not the setup. - Put the pyramid back. When a browser test fails, ask what lower test would have caught this, and write that as well. If a browser test is the only one covering a rule, the rule is probably in the wrong layer.
You will write the checkout journey as a Playwright test, then break it the way a first draft breaks, read the trace and fix it. Work from labs/testing. Each browser test starts its own copy of both servers on 8094 and 8095 with a temporary database, so nothing here touches data/. The output below was recorded on 2026-11-23; times vary a little.
1. Check the disk and the browser.
Chromium and its headless shell take about 530 MB. Check there is room, then point Playwright at a folder inside the lab and install only if it is missing:
cd labs/testing
df -h .
export PLAYWRIGHT_BROWSERS_PATH="$PWD/.playwright-browsers"
ls .playwright-browsers || .venv/bin/playwright install chromium
.venv/bin/pytest tests/e2e -q -p no:randomlydf shows at least 1 GB free. The install, if it runs, downloads Chromium once. Then 1 passed in 1.7s: the lab’s own browser test, tests/e2e/test_checkout_page.py, which starts both servers and places an order. Without PLAYWRIGHT_BROWSERS_PATH the same command prints 1 skipped, because Playwright looks in its default cache and finds no browser. Set the variable in every terminal you use for this chapter.2. Look at the page you are testing.
Start the two apps in two terminals, from labs/testing, and open the page.
.venv/bin/uvicorn fake_provider.app:app --port 8095
.venv/bin/uvicorn checkout.api:app --port 8094Open http://localhost:8094/. Pick Ankara fabric, 6 yards, set the quantity to 2 and press Place order. Then stop both servers with Ctrl-C, because the tests start their own on the same ports.
Order ord_... placed: 2601000 kobo. That is ₦26,010: two lots of ₦12,000, the 5% tier discount, 7.5% VAT and ₦1,500 delivery for a distance of 0 km. The page sends no distance, so it defaults to 0. Note what the page shows: the list loads after the page, from /products, and the button posts to /orders.3. Write the journey and its fixtures.
Create tests/e2e/conftest.py. It shares one browser per test file, gives every test a fresh context with a 5 s deadline and a trace, and keeps the trace only when the test fails:
"""Shared browser fixtures: one browser per test file, one fresh context per test."""
from pathlib import Path
import pytest
from playwright.sync_api import sync_playwright
from tests.e2e.test_checkout_page import servers # noqa: F401 (starts both apps)
TRACES = Path(__file__).resolve().parents[2] / "traces"
@pytest.fixture(scope="module")
def browser():
with sync_playwright() as p:
browser = p.chromium.launch()
yield browser
browser.close()
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
setattr(item, "rep_" + call.when, outcome.get_result()) # item.rep_call.failed
@pytest.fixture
def page(browser, servers, request): # noqa: F811
context = browser.new_context(base_url=servers)
context.set_default_timeout(5_000) # ms, for every wait in this test
context.tracing.start(screenshots=True, snapshots=True, sources=True)
page = context.new_page()
yield page
rep = getattr(request.node, "rep_call", None)
if rep is not None and rep.failed:
TRACES.mkdir(exist_ok=True)
context.tracing.stop(path=str(TRACES / (request.node.name + ".zip")))
else:
context.tracing.stop()
context.close()The browser fixture is module-scoped, not session, on purpose. Playwright’s sync API cannot start a second time while the first is still open in the same process, and the lab’s existing test opens its own. Now create tests/e2e/test_buy_flow.py:
"""The one journey worth a browser: pick a product, pay, see the order."""
import os
import re
import httpx
import pytest
from playwright.sync_api import expect
from tests.e2e.test_checkout_page import _chromium_installed
pytestmark = [
pytest.mark.e2e,
pytest.mark.skipif(not _chromium_installed(), reason="Playwright Chromium not installed"),
]
PROVIDER = "http://127.0.0.1:" + os.environ.get("E2E_PROVIDER_PORT", "8095")
PLACED = re.compile(r"Order (ord_[0-9a-f]{12}) placed: (\d+) kobo")
@pytest.fixture
def provider_mode():
def set_mode(mode):
httpx.post(PROVIDER + "/_admin/mode", json={"mode": mode}).raise_for_status()
yield set_mode
httpx.post(PROVIDER + "/_admin/reset") # leave the provider as we found it
def buy(page, product, qty):
page.goto("/")
page.get_by_label("Product").select_option(label=product) # waits for the option to exist
page.get_by_label("Quantity").fill(str(qty))
page.get_by_role("button", name="Place order").click()
return page.get_by_role("status")
def test_customer_buys_two_ankara_fabrics(page):
status = buy(page, "Ankara fabric, 6 yards (12000 NGN)", 2)
expect(status).to_contain_text(PLACED) # retries until it matches or 5 s pass
order_id, total = PLACED.search(status.inner_text()).groups()
saved = page.request.get(f"/orders/{order_id}") # the same browser session, no page
assert saved.ok
assert saved.json()["total_kobo"] == int(total)
def test_declined_card_shows_the_failure(page, provider_mode):
provider_mode("decline")
status = buy(page, "Shea butter, 500 g (3500 NGN)", 1)
expect(status).to_have_text("Failed: payment_declined").venv/bin/pytest tests/e2e -v -p no:randomlytest_customer_buys_two_ankara_fabrics, test_declined_card_shows_the_failure and the lab’s test_customer_places_an_order, 3 passed in 2.8s. Look at what the file does not contain: no sleep, no wait_for_selector. select_option waited for the catalogue, and expect waited for the order. The first test ends with a check on the saved order through the API, so it covers the page and the database, not the page alone.4. Write the first draft, and make the catalogue slow.
Create tests/e2e/test_naive.py. It is the test most people write first. The route handler holds /products back for the number of seconds in PRODUCTS_DELAY_S, a busy server on demand. It uses page.wait_for_timeout and not time.sleep because a plain sleep would freeze Playwright’s own event handling as well:
"""A browser test written the way the first draft always is."""
import os
import time
import pytest
from tests.e2e.test_checkout_page import _chromium_installed
pytestmark = [
pytest.mark.e2e,
pytest.mark.skipif(not _chromium_installed(), reason="Playwright Chromium not installed"),
]
DELAY_S = float(os.environ.get("PRODUCTS_DELAY_S", "0")) # how slow the catalogue is
def test_naive_buy(page):
def slow_down(route):
page.wait_for_timeout(DELAY_S * 1000) # a busy server; time.sleep would freeze Playwright too
route.continue_()
page.route("**/products", slow_down)
page.goto("/")
time.sleep(0.5) # "the products will be loaded by now"
page.fill("#qty", "2")
page.click("#place")
time.sleep(0.5) # "the order will be placed by now"
assert "placed" in page.inner_text("#result")Run it with three catalogue speeds:
for d in 0 0.3 1; do echo "delay $d s"; PRODUCTS_DELAY_S=$d .venv/bin/pytest tests/e2e/test_naive.py -q -p no:randomly 2>&1 | grep -E "^E |passed|failed"; donedelay 0 s and delay 0.3 s give 1 passed. delay 1 s fails: AssertionError: assert 'placed' in 'Failed: unknown_product', 1 failed. The 0.5 s sleep beat a 0.3 s catalogue and lost to a 1 s one. The page was not broken: the select had no options, so Number("") sent a product id of 0 and the API answered unknown_product. This is the Predict question. On a quick machine the test would pass for months and then fail on the day CI is busy.5. Read the trace.
The failing run saved a trace through the fixture:
ls -l traces
unzip -l traces/test_naive_buy.zip | head -8
.venv/bin/playwright show-trace traces/test_naive_buy.ziptraces/test_naive_buy.zip is about 128 KB. The archive lists trace.trace (the actions), trace.network (every request and response) and a set of resources/ screenshots and DOM snapshots. show-trace opens a window. I confirmed the file and its contents here, and did not open the window; what to look for is the Actions list on the left (Page.goto, Page.fill, Page.click), the Network tab where POST /orders came back as an error, and the After snapshot of the click, which shows Failed: unknown_product. If you have no display, drop the zip onto trace.playwright.dev. Delete the traces/ folder when you have looked.6. Fix it by waiting for the condition.
You have already written the fix: test_buy_flow.py has no sleeps. Prove it holds under the same slow catalogue. Append this to the end of tests/e2e/test_buy_flow.py:
def test_buy_survives_a_slow_catalogue(page):
def slow_down(route):
page.wait_for_timeout(2_000) # the catalogue answers after 2 s
route.continue_()
page.route("**/products", slow_down)
expect(buy(page, "Shea butter, 500 g (3500 NGN)", 1)).to_contain_text(PLACED).venv/bin/pytest tests/e2e/test_buy_flow.py -v -p no:randomly --durations=3
for i in 1 2 3 4 5; do .venv/bin/pytest tests/e2e/test_buy_flow.py -q 2>&1 | tail -1; done3 passed in 4.1s. The slow test shows as the slowest call, about 2.3 s: it waited for the 2 s catalogue and not a moment longer. The happy path and the declined card each take about 0.12 s in the call. The five-run loop prints 3 passed five times (4 to 6 s each), with the random test order on. A one-in-six failure rate would be very likely to show in five runs, so five greens is evidence, not a proof. Run .venv/bin/pytest tests/integration/test_api.py -q --durations=1 for the comparison: three API tests together take about 0.3 s, and the slowest call is 0.01 s. That gap is the price of the join.checkout/api.py, in the PAGE string, change id="place" to id="pay" in the button, and getElementById("place") to getElementById("pay") in the script. Run .venv/bin/pytest tests/e2e/test_naive.py tests/e2e/test_buy_flow.py -q -p no:randomly. The naive test fails with Page.click: Timeout 5000ms exceeded. ... waiting for locator("#place"), 5 s of waiting for an element that is gone. The three tests in test_buy_flow.py stay green, because they find the button by its role and its name, Place order, and that did not change. Now change the visible text instead, from Place order to Pay now, and the result reverses: the role-based tests fail and the id-based one would pass. Neither locator is always right; a role and name tracks what the user sees, which is what you meant to test. Put api.py back as it was (git checkout checkout/api.py), then delete traces/, tests/e2e/conftest.py, tests/e2e/test_buy_flow.py and tests/e2e/test_naive.py so the lab is as you found it.Put the lab back. Run git checkout checkout/api.py (undoing the rename in the break), then delete tests/e2e/conftest.py, tests/e2e/test_naive.py, tests/e2e/test_buy_flow.py and the traces/ folder. Keep .playwright-browsers/ if you installed Chromium: it is ignored by git and the project needs it.
After the Friday outage Nokuthula's team wants browser coverage. Ramla lists fourteen flows: buying, a declined card, a promo code, the delivery bands, a stock-out, an address change, a seller adding a product and eight more. Each browser test takes about 3 s with its setup, and the team's pipeline budget for E2E is 60 s. The pricing and stock rules already have unit and integration tests. What do they do?
- DOC Playwright for Python: Installation
How to install the package and the browsers, and the pytest plugin. Read the install steps and the first example. This lab writes its own fixtures, so you can skip the plugin's own options on a first pass.
- DOC Playwright: Best Practices
The project's own advice: test user-visible behaviour, isolate each test, use locators and web-first assertions, and debug CI failures with the trace viewer. Read the whole page; it is short and every section matches a step in the lab.
- DOC Playwright: Auto-waiting
The table of actionability checks per action: what click, fill and select_option each wait for. Read it to learn which waits you get for free, and so which sleeps you can delete.
- DOC Playwright: Trace viewer
How to record a trace with context.tracing, open it with playwright show-trace or at trace.playwright.dev, and what each panel shows. Read 'Recording a trace' and 'Opening the trace'; skip the sections on other languages' test runners.
- POST Just Say No to More End-to-End Tests Mike Wacker, 2015
Google Testing Blog, 22 April 2015. The argument that end-to-end tests are slow, flaky and expensive to debug, and that a team should keep the pyramid and limit browser tests to a few broad flows. Read it before you decide how many journeys the Decide above should keep.
- POST TestPyramid Martin Fowler, 2012
The short note that says UI-driven end-to-end tests are brittle, expensive and slow, so a suite should hold far more fast tests below them. Its last advice, to reproduce a bug a high-level test finds with a unit test, is the fourth habit in this chapter. Read it all; it takes two minutes.
- POST BroadStackTest Martin Fowler, 2013
A short note that names the test this chapter is about, gives its costs and says to replace remote systems with doubles checked by contract tests. Read all of it; it takes two minutes.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.