Skip to content
Visual explainer 4h to learn 4 steps

End-to-end tests with Playwright

Write E2E tests for key user flows and run them in CI.

By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.

Topic 32 of 36

In short

End-to-end tests drive a real browser through your running app, covering full user flows like signing in and checking out. Playwright auto-waits for elements and runs in CI on every push.

Explained simply

An end-to-end test, or E2E test, checks your whole app the way a real user meets it: a real browser opens your site, clicks links, fills forms and checks what appears. If the database, the server and the page all work together, the test passes.

Playwright is a tool from Microsoft for writing these tests. One test can run in Chromium, Firefox and WebKit, the engine behind Safari. It can run with a visible window while you watch, or headless (without a window) on a server.

Older E2E tools were famous for flaky tests that passed one day and failed the next, often because the test clicked before the page was ready. Playwright waits automatically until an element is visible and ready before acting, which removes most of that flakiness.

E2E tests are slower than unit tests, so you write only a handful, for the flows that must never break: signing in, the main task of your app, and paying if you take payments. Then you run them on every pull request.

Press Play on a diagram to walk through it one step at a time.

SequenceAn E2E test run
Playwright test
Real browser
Your app
  1. 1Launch and goto('/login')
    Playwright test to Real browser: Launch and goto('/login')
  2. 2Request page
    Real browser to Your app: Request page
  3. 3Render login form
    Your app to Real browser: Render login form
  4. 4Fill fields, click Sign in
    Playwright test to Real browser: Fill fields, click Sign in
  5. 5Submit credentials
    Real browser to Your app: Submit credentials
  6. 6Redirect to dashboard
    Your app to Real browser: Redirect to dashboard
  7. 7Expect heading visible
    Playwright test to Real browser: Expect heading visible
MapWhat playwright.config.ts controls
playwright.config.ts
  • testDir and timeouts
    • Where tests live
    • 30 s per test by default
  • use
    • baseURL
    • trace and screenshot
    • storageState
  • projects
    • setup
    • chromium, firefox, webkit
    • Mobile devices
  • webServer
    • Command to start the app
    • URL to wait for
  • CI behaviour
    • retries
    • workers
    • reporter

In depth

Installing Playwright and recording a first test

Run npm init playwright@latest in your project. It asks a few questions, then creates playwright.config.ts, a tests folder with an example, optionally a GitHub Actions workflow, and downloads browser builds. On a new machine or CI runner, npx playwright install --with-deps installs the browsers plus the system libraries they need.

npx playwright codegen http://localhost:3000 opens a browser and an inspector window. Everything you click and type is turned into test code using recommended locators, which you can copy into a file. Treat it as a starting point: rename the test, remove extra steps, and add expect assertions for what should be true after each important action. Run tests with npx playwright test, open the interactive UI mode with --ui, or step through one test with --debug. After a run, npx playwright show-report opens the HTML report.

  • npx playwright test tests/login.spec.ts --project=chromium
  • npx playwright test --headed shows the browser
  • npx playwright test -g "sign in" filters by title

Locators, auto-waiting and web-first assertions

A locator, such as page.getByRole("button", { name: "Save" }), is a description of how to find an element, not the element itself. Playwright looks it up again every time you use it, so it survives re-renders. Locators are strict: if an action matches more than one element, Playwright throws instead of guessing. Narrow it with a parent locator, filter({ hasText }), or a more specific name.

Before every action Playwright runs actionability checks. For a click, the element must be attached, visible, stable (not animating), able to receive events (not covered by another element) and enabled. It retries until these pass or the action times out. Assertions like await expect(locator).toBeVisible(), toHaveText, toHaveValue and expect(page).toHaveURL also retry, by default for up to 5 seconds. That is why you should never need page.waitForTimeout: wait for a state, not for a number of seconds.

FlowWhat happens inside locator.click()
  1. 1
    Resolve locator

    Exactly one element, or a strictness error

  2. 2
    Check actionable

    Visible, stable, enabled, not covered

  3. 3
    Retry if not

    Until the action timeout

  4. 4
    Scroll into view

    Then click at its centre

  5. 5
    Next step

    Assertions retry the same way

Testing sign-in once and reusing the session

Every Playwright test gets a fresh browser context, like a new private window with no cookies, so tests cannot affect each other. That isolation is good, but logging in through the form before every test is slow. The recommended pattern is a setup project: one test signs in, then saves cookies and local storage with page.context().storageState({ path: "playwright/.auth/user.json" }).

In playwright.config.ts, other projects declare dependencies: ["setup"] and use: { storageState: "playwright/.auth/user.json" }, so they start already signed in. Keep the auth folder in .gitignore, because it contains a real session. Still keep one test that goes through the sign-in form itself, including a wrong password, so the login page is covered. Use a dedicated test account with credentials from environment variables, never a real user's account.

SequenceSetup project and dependent tests
setup project
App
Auth file
Other tests
  1. 1Fill login form, submit
    setup project to App: Fill login form, submit
  2. 2Set session cookie
    App to setup project: Set session cookie
  3. 3storageState saved
    setup project to Auth file: storageState saved
  4. 4New context loads the state
    Other tests to Auth file: New context loads the state
  5. 5Open /dashboard, already signed in
    Other tests to App: Open /dashboard, already signed in

Running Playwright in CI without flakiness

The webServer option in the config starts your app before the tests, for example command: "npm run build && npm run start" with url: "http://localhost:3000" and reuseExistingServer: !process.env.CI. Test against a production build, which behaves like the real site, rather than the dev server. Set use.baseURL so tests can call page.goto("/login").

The generated config already sets retries: 2 and workers: 1 when the CI variable is present, and trace: "on-first-retry". A trace records every action with DOM snapshots, network calls and console logs; upload the playwright-report folder as a CI artifact and open a trace with npx playwright show-trace or at trace.playwright.dev. A test that passes only on retry is reported as flaky: fix it rather than ignore it. Common causes are shared test data, missing awaits and depending on test order. Give each test its own data, or reset the database before the run.

  • retries: process.env.CI ? 2 : 0
  • use: { baseURL: "http://localhost:3000", trace: "on-first-retry" }
  • page.route(urlPattern, route => route.fulfill({ json: data })) mocks one API call

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Install Playwright and record a test~1h
  2. 2
    Test sign-in and a key user flow~1h
  3. 3
    Use locators and auto-waiting~1h
  4. 4
    Run Playwright in CI~1h

Key points

  • Test a few critical flows end to end; cover details with faster unit tests.
  • Locators like getByRole auto-wait, so avoid fixed sleeps.
  • codegen records your clicks into a starting test script.
  • Run tests headless in CI and keep traces to debug failures.

Key terms

Tap a card to flip it. 0/5 known

Examples

ts
import { test, expect } from '@playwright/test';

test('user can sign in', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('demo@example.com');
  await page.getByLabel('Password').fill('correct-horse');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
});

// Run: npx playwright test
// Record: npx playwright codegen localhost:3000

A sign-in flow using role and label locators.

A setup project that signs in once

Step 1: a file named auth.setup.ts uses test as setup and signs in through the real form. Step 2: it waits until the URL shows the dashboard, proving the login worked. Step 3: it saves the browser state to a file. Step 4: in the config, the chromium project depends on setup and loads that file, so every other test starts signed in.

ts
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';

setup('sign in', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.E2E_EMAIL!);
  await page.getByLabel('Password').fill(process.env.E2E_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL(/dashboard$/);
  await page.context().storageState({ path: authFile });
});
// playwright.config.ts, projects:
// { name: 'setup', testMatch: /.*\.setup\.ts/ },
// { name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: authFile }, dependencies: ['setup'] }

Running E2E tests on every pull request

Step 1: check out the code and install dependencies from the lockfile. Step 2: install only the Chromium browser and its system libraries to save time. Step 3: run the tests; the config's webServer builds and starts the app. Step 4: always upload the HTML report, unless the run was cancelled, so you can open traces of any failure.

yaml
name: E2E
on: [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/, retention-days: 7 }

Quick reference

  • npm init playwright@latest sets up config, example tests and browsers
  • npx playwright codegen localhost:3000 records actions as test code
  • npx playwright test --ui for an interactive runner; --debug to step through
  • page.getByRole / getByLabel / getByText are the preferred locators
  • await expect(locator).toBeVisible() retries; never use waitForTimeout
  • storageState plus a setup project: sign in once, reuse everywhere
  • trace: "on-first-retry" then npx playwright show-trace trace.zip
  • webServer in the config starts the app before the tests

Common mistakes

  • Using waitForTimeout instead of relying on auto-waiting assertions.
  • Writing E2E tests for every edge case, making the suite slow and flaky.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does Playwright do if page.getByRole("button", { name: "Save" }).click() matches two buttons?

Question 2

2How do most tests start already signed in without using the login form each time?

Question 3

3A test fails only in CI. What is the best first debugging tool?

Question 4

4Which of these is NOT part of Playwright's actionability checks before a click?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a test that opens the home page and checks that the main heading Habit Tracker is visible and the page title contains Habit.

  2. Exercise 2medium

    Test that signing in with a wrong password shows an alert containing Invalid and keeps the user on /login.

  3. Exercise 3hard

    A signed-in user adds a habit called Read 10 pages and sees it in the list. Make the name unique per run so repeated runs do not clash.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Playwright or Cypress?
Both are good E2E tools. Playwright supports Chromium, Firefox and WebKit, runs tests in parallel for free and handles multiple tabs and origins easily, which is why many new projects choose it.
How many E2E tests should I write?
Usually a small number, one per critical user flow such as sign-in, the main task and checkout. Cover details and edge cases with faster unit and component tests.
Should E2E tests use a real database?
Yes, a dedicated test database that you seed or reset before the run, never production. You can mock external third-party APIs with page.route to keep tests stable.
Why does my test pass locally but time out in CI?
CI machines are slower and start from a clean state: missing browsers, missing environment variables, a server that is not built, or data that exists only on your laptop. Check the trace and the webServer output.

Go deeper

ShareXLinkedInWhatsApp