Skip to the content

Lesson 186 of 296

End-to-end tests with Playwright

What you will learn

  • What end-to-end tests are for
  • Playwright basics: pages, locators, actions, assertions
  • Auto-waiting and web-first assertions
  • A login and checkout journey
  • Mocking network routes, authentication state and the Page Object pattern
  • Running E2E tests in CI and avoiding flaky tests
On this page

What are E2E tests?

End-to-end (E2E) tests run the real app in a real browser and act like a user: open a page, click, type, check the result. They catch problems that unit and integration tests miss: broken routing, wrong environment configuration, a server action that fails, CSS that hides a button.

They are slower and harder to maintain, so write a few for the most important user journeys: sign up, log in, search, checkout, payment.

Playwright

Playwright (by Microsoft) is the most popular E2E tool today. It drives Chromium, Firefox and WebKit (Safari's engine) from one API, in parallel, with automatic waiting. Cypress is the main alternative.

Set up: npm init playwright@latest. Tests live in a folder such as e2e and run with npx playwright test.

A first test

TypeScript
import { test, expect } from "@playwright/test";

test("home page shows the course title and links to lessons", async ({ page }) => {
  await page.goto("http://localhost:3000/");
  await expect(page).toHaveTitle(/JobPrep/);
  await expect(page.getByRole("heading", { level: 1 })).toHaveText("Become job-ready");

  await page.getByRole("link", { name: "Start learning" }).click();
  await expect(page).toHaveURL(/\/lessons$/);
});
  • page is a browser tab, given to each test fresh.
  • Locators like page.getByRole, getByLabel, getByText and getByTestId work like React Testing Library queries. Same priority: role and label first.
  • Actions: click(), fill("text"), press("Enter"), check(), selectOption("pro"), setInputFiles(...).

Auto-waiting and web-first assertions

Playwright waits automatically: before clicking, it waits until the element exists, is visible, stable and enabled. Assertions like await expect(locator).toHaveText(...) retry until they pass or time out (5 seconds by default).

So you almost never need manual waits. Avoid page.waitForTimeout(2000): fixed sleeps make tests slow and flaky. Wait for something meaningful instead: text appears, URL changes, a response arrives.

A journey: log in and buy

TypeScript
import { test, expect } from "@playwright/test";

test("a signed-in user can add a product to the basket and check out", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("test.user@example.com");
  await page.getByLabel("Password").fill("correct-horse-battery");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("navigation")).toContainText("My account");

  await page.goto("/products/mug");
  await page.getByRole("button", { name: "Add to basket" }).click();
  await expect(page.getByRole("status")).toHaveText("Added to basket");

  await page.getByRole("link", { name: /Basket \(1\)/ }).click();
  await page.getByRole("button", { name: "Checkout" }).click();
  await expect(page.getByRole("heading", { name: "Order confirmed" })).toBeVisible();
});

page.goto("/login") works with a baseURL set in playwright.config.ts. The config can also start your app automatically before tests with the webServer option.

Mocking network routes

To test the UI against an error without breaking the real back end, intercept requests:

TypeScript
import { test, expect } from "@playwright/test";

test("shows an error when products fail to load", async ({ page }) => {
  await page.route("**/api/products", (route) =>
    route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: "down" }) })
  );
  await page.goto("/products");
  await expect(page.getByRole("alert")).toContainText("Could not load products");
});

Mostly, E2E tests should hit a real test back end with a seeded test database, so they prove the whole system works. Use route mocking for hard-to-create situations (errors, slow responses, third-party services such as payments).

Logging in once

Logging in through the UI in every test is slow. Playwright can log in once in a setup step, save the cookies and storage to a file (storageState), and reuse that state in other tests.

The Page Object pattern

Wrap a page's locators and actions in a class, so tests read like steps and a UI change is fixed in one place:

TypeScript
import type { Page } from "@playwright/test";

export class LoginPage {
  constructor(private readonly page: Page) {}

  async goto() {
    await this.page.goto("/login");
  }

  async signIn(email: string, password: string) {
    await this.page.getByLabel("Email").fill(email);
    await this.page.getByLabel("Password").fill(password);
    await this.page.getByRole("button", { name: "Sign in" }).click();
  }
}

In a test: const login = new LoginPage(page); await login.goto(); await login.signIn(email, password);.

Debugging and CI

ToolUse
npx playwright test --uiUI mode: run, watch and step through tests
npx playwright codegenRecords your clicks and writes test code
Trace viewerA recording of every step with DOM snapshots, network and console; enable traces on the first retry in CI
Screenshots and videosSaved on failure

In CI (Lesson 251), run Playwright in a pipeline on every pull request, against a preview deployment or a locally started app. Install browsers with npx playwright install --with-deps.

Avoiding flaky E2E tests

  • Use role and label locators, not long CSS selectors that break when markup changes.
  • Never use fixed sleeps; rely on auto-waiting and web-first assertions.
  • Make each test independent: create its own data and do not rely on another test running first.
  • Reset or seed the test database.
  • Mock unreliable third-party services.

How to say it in an interview

"End-to-end tests run the real app in a real browser for the critical journeys like signup, login and checkout, so I keep a small number of them. I use Playwright with role and label locators, rely on its auto-waiting and retrying web-first assertions instead of sleeps, and keep tests independent with seeded data. I reuse login state with storageState, use page objects so tests read like user steps, mock only hard cases like errors or payment providers with page.route, and run them in CI with traces on retry for debugging."

Key words

WordMeaning
E2E testA test of the whole app in a real browser
LocatorPlaywright's way to find elements
Auto-waitingWaiting for elements to be ready before acting
Web-first assertionAn assertion that retries until it passes or times out
storageStateSaved login cookies and storage reused across tests
Page ObjectA class wrapping a page's locators and actions
TraceA step-by-step recording of a test run

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.