End-to-end tests drive the real application in a real browser: they click, type, navigate, and read the page the way a person does. They're the only automated tests that check the whole journey works together, from HTML and JavaScript through the API to the database. They're also the slowest and, written carelessly, the flakiest tests you'll own. This lesson uses Playwright to automate real user workflows, and centers on the principle its documentation emphasizes: test user-visible behavior, keep every test isolated, and let the tool wait for you. You'll see a real failing test that caught an accessibility bug, and the fix.
Before you start
You should know the testing levels from lesson 2 and integration testing from Integration Testing: APIs, Databases, and Real Application Dependencies. You need Node.js and a web page or app to test; the example is a small sign-up page.
Setting up Playwright
npm init playwright@latestThe initializer adds @playwright/test, a config file, an example test, and downloads browser builds for Chromium, Firefox, and WebKit (the engine behind Safari). A minimal config starts your app automatically before the tests:
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "e2e",
use: { baseURL: "http://127.0.0.1:4173", trace: "on-first-retry" },
webServer: { command: "npm run preview -- --port 4173", url: "http://127.0.0.1:4173", reuseExistingServer: !process.env.CI },
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
{ name: "webkit", use: { ...devices["Desktop Safari"] } },
{ name: "mobile", use: { ...devices["Pixel 7"] } },
],
});Test what users see, not how it's built
Playwright's best-practices guidance is to test user-visible behavior: what the end user sees and interacts with. Users don't know about CSS classes, component names, or element IDs; they see a button labeled "Sign up," a field labeled "Email," and a message. Tests that find elements the same way:
- don't break when the markup is refactored;
- fail when something a user depends on actually breaks;
- and quietly check accessibility, because the accessible name is how assistive technology finds things too.
Playwright's recommended locators reflect this, in rough order of preference:
page.getByRole("button", { name: "Sign up" }); // role and accessible name
page.getByLabel("Email"); // form fields by their label
page.getByText("Thanks! Check your inbox."); // visible text
page.getByTestId("price-total"); // an explicit test id, when nothing user-facing fitsAvoid locators like page.locator("div.form > button.btn-primary:nth-child(2)"). They describe the implementation, and break whenever it changes.
A first workflow test, and a real failure
The page under test is a small sign-up form. After submitting, it shows a message. The tests describe two user journeys:
import { expect, test } from "@playwright/test";
test("a visitor signs up with a valid email", async ({ page }) => {
await page.goto("/");
await page.getByLabel("Email").fill("ada@example.test");
await page.getByRole("button", { name: "Sign up" }).click();
await expect(page.getByRole("status")).toHaveText("Thanks! Check your inbox.");
});
test("an invalid email shows an error", async ({ page }) => {
await page.goto("/");
await page.getByLabel("Email").fill("ada@");
await page.getByRole("button", { name: "Sign up" }).click();
await expect(page.getByRole("status")).toHaveText("Enter a valid email address.");
});The tests expect the message to be a status: a live region that screen readers announce when it changes. Running them (Playwright 1.64):
Running 2 tests using 1 worker
✘ 1 e2e/signup.spec.ts:3:1 › a visitor signs up with a valid email (5.6s)
✘ 2 e2e/signup.spec.ts:10:1 › an invalid email shows an error (5.1s)
1) e2e/signup.spec.ts:3:1 › a visitor signs up with a valid email
Error: expect(locator).toHaveText(expected) failed
Locator: getByRole('status')
Expected: "Thanks! Check your inbox."
Timeout: 5000ms
Error: element(s) not found
Call log:
- Expect "toHaveText" getByRole('status') with timeout 5000ms
- waiting for getByRole('status')
5 | await page.getByLabel("Email").fill("ada@example.test");
6 | await page.getByRole("button", { name: "Sign up" }).click();
> 7 | await expect(page.getByRole("status")).toHaveText("Thanks! Check your inbox.");
| ^Reading the failure
The form worked: the text "Thanks! Check your inbox." did appear on the screen. But Playwright couldn't find any element with the role status. The page's markup was:
<p id="message"></p>A sighted user sees the message. A screen reader user hears nothing, because a plain paragraph that changes isn't announced. The test, by asking for the element the way assistive technology does, found a real accessibility defect that a test using #message would have missed.
The fix is one attribute:
<p id="message" role="status"></p> ✓ 1 e2e/signup.spec.ts:3:1 › a visitor signs up with a valid email (149ms)
✓ 2 e2e/signup.spec.ts:10:1 › an invalid email shows an error (102ms)
2 passedWaiting: let Playwright do it
Most flaky E2E tests are timing problems: the test checks before the page has updated. Playwright prevents most of these:
- Actions auto-wait:
click()waits until the element is visible, enabled, stable, and able to receive clicks. - Web-first assertions retry:
await expect(locator).toHaveText(...)keeps checking until it passes or the timeout expires (5 seconds by default, as in the failure above).
So never add fixed sleeps:
// Don't: slow when the app is fast, and still flaky when it's slower than usual
await page.waitForTimeout(3000);
// Do: wait for the thing the user would wait for
await expect(page.getByRole("heading", { name: "Your bookings" })).toBeVisible();Also avoid checking a value once without retrying, such as expect(await locator.textContent()).toBe(...); it reads the text a single time and doesn't wait.
Isolation: every test starts clean
Playwright runs each test in a fresh browser context, like a new incognito profile, with its own cookies and storage. Keep that isolation in your data too:
- Each test creates the data it needs (through the API or database is faster than through the UI), with unique values so tests can run in parallel.
- Tests never depend on another test having run first.
- Don't share a signed-in account whose state tests modify; give each test its own user, or reset it.
Signing in once
Signing in through the UI in every test is slow. Playwright can sign in once in a setup project, save the session, and reuse it:
import { expect, test as setup } from "@playwright/test";
setup("sign in", 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("heading", { name: "Your bookings" })).toBeVisible();
await page.context().storageState({ path: "e2e/.auth/user.json" });
});Add the setup as a project that others depend on, and point their storageState at the saved file. Keep the .auth folder out of Git, and use a dedicated test account in a test environment, never a real user's credentials.
Don't test what you don't control
Playwright's guidance also warns against testing third-party sites and services directly: a payment provider's page or a social login can change or rate-limit you at any time. Mock those network calls with page.route() or use the provider's test mode, and test your own side of the integration.
Debugging failures
npx playwright test --uiopens an interactive runner where you can watch each step.npx playwright test --debugsteps through a test with the inspector.- Traces record every action, network request, console message, and a DOM snapshot at each step. With
trace: "on-first-retry", CI keeps a trace for any test that failed once; open it withnpx playwright show-trace. npx playwright codegenrecords your clicks as test code. It's a good starting point, but review the locators it chooses.
What to automate end to end
E2E tests are expensive, so choose them by value:
- the critical journeys that make or lose money or trust: sign-up, sign-in, checkout, booking, password reset;
- flows that cross many components, where lower-level tests can't see the whole;
- a smoke subset that runs after every deployment.
Push edge cases (every invalid email format, every boundary) down to unit tests (lesson 3).
Common mistakes and troubleshooting
- CSS or XPath locators. Use roles, labels, and text.
- Fixed sleeps. Use web-first assertions.
- Tests that depend on each other or on shared data. Isolate them.
- Too many E2E tests. Keep them for critical journeys; test details lower down.
- Testing third-party pages. Mock them or use their test mode.
- "Strict mode violation: resolved to 2 elements." Your locator matches several elements; make it more specific, for example with
{ name: ... }or by narrowing to a region. - Passes locally, fails in CI. Check the viewport, fonts, time zone, and data. Open the CI trace.
Practical exercise: automate a journey
- Initialize Playwright in a small web project you control.
- Write tests for one success journey and one error journey using only role, label, and text locators.
- Break the page on purpose: remove a
<label>or therole="status". Do your tests fail? What would a user with a screen reader experience? - Add a setup project that signs in once and reuses the session.
- Run the tests in Chromium, Firefox, and WebKit, and with the mobile profile.
- Make one test fail in CI, download the trace, and find the failing step in the trace viewer.
Key takeaways
- E2E tests drive real browsers through real journeys; write them for critical flows, not every case.
- Test user-visible behavior with role, label, and text locators; it also catches accessibility defects.
- Playwright auto-waits for actions and retries assertions; never use fixed sleeps.
- Keep tests isolated: fresh contexts, own data, no ordering dependencies.
- Don't test third-party services directly; debug with the UI mode and traces.
References
- Playwright: Best Practices (opens in a new tab)
- Playwright: Locators (opens in a new tab)
- Playwright: Auto-waiting (opens in a new tab)
- Playwright: Authentication (opens in a new tab)
- Playwright: Trace viewer (opens in a new tab)
- MDN: ARIA status role (opens in a new tab)
What's next
So far, tests have been written after the code. Test-Driven Development (TDD), Refactoring, and Maintainable Test Suites flips the order and shows how tests can shape better design.

