Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 74 ยท Quality and Performance

End-to-End Testing with Playwright

Test a whole Angular app in a real browser with Playwright. Learn locators, auto-waiting, running against ng serve, page objects, mocking APIs and CI, with runnable logic stand-ins.

Unit tests check one class or component at a time. They are fast, but they cannot tell you whether the whole app works: whether the router really shows the right page, whether the login form really talks to the service, whether the button is really clickable. End-to-end (E2E) tests answer those questions by driving a real browser the way a user does: open a URL, click, type, and look at what is on the screen.

This lesson uses Playwright, a popular E2E tool that works with any web app, Angular included. Cypress and WebdriverIO follow the same ideas, so what you learn here transfers. You should have read Testing Angular Apps first, because the lesson explains where E2E tests fit in the bigger picture.

Real versus stand-in. Playwright needs a real browser and a running app, so the bash, typescript and yaml blocks are real code to read and copy. The runnable examples re-create the ideas that make E2E tests reliable (auto-waiting with retries, locators that describe what a user sees, and a page object) with small fake pages and timers. They are not Playwright.

Where E2E tests fit

A healthy test suite is shaped like a pyramid: many unit tests at the bottom, fewer component tests in the middle, and only a few E2E tests at the top.

flowchart TD
  E["E2E tests<br/>few, slow, real browser, whole app"] --> C["Component and integration tests<br/>TestBed, harnesses"]
  C --> U["Unit tests<br/>many, fast, one class"]

The higher a test sits, the more it proves and the slower and more fragile it is. Keep E2E for the journeys that must never break.

Good candidates are critical user journeys: sign up, log in, add an item to the cart and check out, save a form. Bad candidates are details such as "a pipe formats a date", which a unit test covers in milliseconds.

Setting up Playwright

Add Playwright to an existing Angular project with its own initializer. It creates a config file, an example test and a tests folder:

Terminal
npm init playwright@latest
npx playwright install --with-deps chromium

Then tell Playwright how to start your app. The webServer option runs ng serve before the tests and waits until the URL answers:

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

export default defineConfig({
  testDir: './e2e',
  fullyParallel: true,
  retries: process.env['CI'] ? 2 : 0,
  reporter: [['html', { open: 'never' }]],
  use: {
    baseURL: 'http://localhost:4200',
    trace: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'mobile', use: { ...devices['Pixel 7'] } },
  ],
  webServer: {
    command: 'npm run start',
    url: 'http://localhost:4200',
    reuseExistingServer: !process.env['CI'],
  },
});

baseURL lets tests write page.goto('/'). trace: 'on-first-retry' records a replayable trace (screenshots, network, DOM) for failures, which is the best debugging tool Playwright has. reuseExistingServer means that on your laptop an already running ng serve is reused, while CI always starts a fresh one.

For a faster and more production-like target you can serve the built app instead of the dev server: ng build and then any static server with a fallback to index.html, so deep links to client-side routes work.

Your first test

A test gets a page, opens a URL, interacts and then makes assertions:

TypeScript
// e2e/todo.spec.ts
import { expect, test } from '@playwright/test';

test('adds and completes a todo', async ({ page }) => {
  await page.goto('/');

  await page.getByRole('textbox', { name: 'New todo' }).fill('Write E2E tests');
  await page.getByRole('button', { name: 'Add' }).click();

  const item = page.getByRole('listitem').filter({ hasText: 'Write E2E tests' });
  await expect(item).toBeVisible();

  await item.getByRole('checkbox').check();
  await expect(page.getByText('0 items left')).toBeVisible();
});

Run it with npx playwright test, add --ui for an interactive runner or --headed to watch the browser.

Locators: find things like a user does

Notice that the test never uses a CSS class or an Angular selector. getByRole, getByLabel, getByText and getByPlaceholder look for what a user perceives: a button called "Add", a textbox labelled "New todo". This has two benefits. Tests keep working when you restyle or refactor the markup, and a failing getByRole often reveals a real accessibility problem, because an element without a proper role or label is hard for screen readers too (see Security and Accessibility).

When no good role or text exists, add a stable test attribute and use getByTestId:

HTML
<button type="button" data-testid="checkout" (click)="checkout()">Pay</button>
TypeScript
await page.getByTestId('checkout').click();

Prefer roles and labels first, test ids second, and CSS or XPath selectors last.

Auto-waiting and web-first assertions

Angular apps update asynchronously: data arrives later, a route loads a lazy chunk, a @defer block appears after a trigger. The beginner's mistake is to add waitForTimeout(2000) everywhere. Do not. Playwright auto-waits: before a click it waits until the element exists, is visible, stable and enabled, and expect(locator) assertions retry until they pass or a timeout (5 seconds by default) expires.

The stand-in below shows that mechanism in a few lines: a fake page whose element appears after 300 ms, a waitFor helper that polls, and what happens when it times out.

TypeScript Auto-waiting: retry an assertion until it passes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Real Playwright is smarter (it uses the browser's own events and checks actionability), but the shape is the same. The lesson for your tests: assert on the outcome and let the tool wait. Never sleep for a guessed time.

Page objects: keep tests readable

When many tests use the same screen, put its locators and actions into a small class. If the markup changes, you fix one file:

TypeScript
// e2e/pages/todo-page.ts
import { expect, Locator, Page } from '@playwright/test';

export class TodoPage {
  readonly input: Locator;
  readonly addButton: Locator;

  constructor(private readonly page: Page) {
    this.input = page.getByRole('textbox', { name: 'New todo' });
    this.addButton = page.getByRole('button', { name: 'Add' });
  }

  async open(): Promise<void> {
    await this.page.goto('/');
  }

  async add(title: string): Promise<void> {
    await this.input.fill(title);
    await this.addButton.click();
  }

  async expectRemaining(count: number): Promise<void> {
    await expect(this.page.getByText(`${count} item`)).toBeVisible();
  }
}
TypeScript
test('counts remaining items', async ({ page }) => {
  const todos = new TodoPage(page);
  await todos.open();
  await todos.add('One');
  await todos.add('Two');
  await todos.expectRemaining(2);
});

The test now reads like the journey it checks. Keep assertions in the test (or in clearly named expect... methods) and keep page objects free of test logic.

TypeScript A page object over a fake page

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Test data, login and the network

E2E tests are only reliable when the data is predictable. Three habits help:

  • Control the backend. Either run the tests against a test database that you reset, or mock the network so the test does not depend on a real server. Playwright can intercept requests:
TypeScript
test('shows an error when the API fails', async ({ page }) => {
  await page.route('**/api/forecast*', route =>
    route.fulfill({ status: 500, json: { message: 'Server error' } }),
  );
  await page.goto('/weather');
  await expect(page.getByRole('alert')).toContainText('Something went wrong');
});

This is the easy way to test the unhappy paths from HttpClient: Requests and Responses that a healthy server never produces.

  • Log in once. Do not click through the login form in every test. Log in in a setup step, save the browser's storage state to a file and reuse it:
TypeScript
// e2e/auth.setup.ts
import { test as setup } from '@playwright/test';

setup('log 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 page.waitForURL('/dashboard');
  await page.context().storageState({ path: 'e2e/.auth/user.json' });
});

Keep credentials in environment variables or CI secrets and add e2e/.auth to .gitignore.

  • Keep tests independent. Each test should create the data it needs and not rely on another test running first. Playwright runs files in parallel, and order-dependent tests fail randomly.

Running in CI

On a CI server install the browser, run the tests and keep the report when something fails:

YAML
# .github/workflows/e2e.yml
name: e2e
on: [push, pull_request]
jobs:
  e2e:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: npm }
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test
      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: playwright-report
          path: playwright-report/

If a test fails in CI but passes locally, download the report and open the trace: it shows every step with a screenshot, so you rarely need to guess. Treat a flaky test as a bug to fix (usually a missing wait on the outcome, shared data or a timing assumption), not as something to retry forever.

Start with three to five tests: one happy path per critical journey, plus one failure case. A small, stable suite that runs on every pull request is worth more than a big suite that people ignore.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which kind of test belongs at the top of the testing pyramid?

    E2E tests run the whole app in a real browser. They prove a lot but are slow and more fragile, so keep them few and focused on journeys that must not break.
  2. 2. Why does Playwright code usually find elements with getByRole and getByLabel?

    Role and label locators match how people and assistive technology see the page. CSS classes change often; roles and labels rarely do.
  3. 3. An item appears 300 ms after navigation. What is the best way to test it?

    Playwright auto-waits and retries web-first assertions. A fixed sleep is either too short (flaky) or too long (slow).
  4. 4. What does the webServer option in playwright.config.ts do?

    webServer runs a command, waits until the URL responds, and stops the server afterwards, so one command runs the whole suite.

Summary

  • E2E tests drive a real browser through the whole app; keep them few and aimed at critical journeys.
  • Playwright starts your app with webServer, and tests use baseURL, page.goto, locators and expect.
  • Prefer getByRole, getByLabel and getByText; use data-testid when nothing better exists.
  • Never sleep: auto-waiting and retrying assertions handle asynchronous Angular updates.
  • Use page objects for repeated screens, page.route to mock failing APIs, and a saved storage state to log in once.
  • In CI install the browser, run the suite and upload the report and traces.
  • The Playwright code is real and read-only here; the runnable examples are stand-ins for the retry and page-object ideas.

Next: SSR, Hydration and Prerendering