Broken checkouts, silent login regressions, and CSS overlay bugs rarely show up in unit tests. End-to-end (E2E) browser testing catches what unit tests miss by driving a real browser against your built application. Yet many teams abandon E2E suites because brittle CSS selectors and arbitrary sleep() calls turn CI pipelines into flaky noise generators.
Playwright eliminates most of that historical flakiness when used as designed: cross-browser engines out of the box, isolated browser contexts per test, auto-waiting locators, and rich trace artifacts when a CI run fails. In this tutorial, you will bootstrap a TypeScript Playwright suite, write resilient tests using role-based locators and web-first assertions, isolate authentication state and API mocks, run sharded suites in GitHub Actions, and debug failures with Trace Viewer.
Initializing a Playwright TypeScript Suite Across Chromium, Firefox, and WebKit
According to the Playwright installation documentation, Playwright supports Chromium, WebKit, and Firefox across Linux, macOS, and Windows with built-in mobile viewport emulation, parallel execution, and per-test browser context isolation.
Initialize Playwright inside an existing TypeScript web project using the official CLI, then tune playwright.config.ts so local runs stay fast while CI runs automatically capture traces on retries and launch your dev or preview server.
bash# Initialize Playwright with TypeScript and GitHub Actions workflow template
npm init playwright@latest -- --lang=ts --quiet
# Run the starter suite locally in headless mode
npx playwright test
Here is a clean, production-oriented playwright.config.ts configuration targeting desktop Chromium, Firefox, and WebKit alongside a mobile Chromium viewport.
typescriptimport { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests/e2e",
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 2 : undefined,
reporter: [["html", { open: "never" }], ["list"]],
use: {
baseURL: process.env.BASE_URL ?? "http://127.0.0.1:3000",
trace: "on-first-retry",
screenshot: "only-on-failure",
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
{ name: "webkit", use: { ...devices["Desktop Safari"] } },
{ name: "mobile-chrome", use: { ...devices["Pixel 7"] } },
],
webServer: {
command: "npm run preview -- --port 3000",
url: "http://127.0.0.1:3000",
reuseExistingServer: !process.env.CI,
},
});
Writing Non-Flaky Tests with Role Locators and Web-First Assertions
The fastest way to build a brittle test suite is querying internal DOM structure like div.card > span:nth-child(3) or asserting synchronous values immediately after clicking a button. The Playwright Best Practices guide emphasizes three core habits: test user-visible behavior, locate elements using user-facing attributes such as ARIA roles and accessible labels, and use auto-retrying web-first assertions.
- Prefer
getByRole,getByLabel, andgetByText: These locators verify accessibility semantics at the same time they select elements, catching missing labels or broken button roles early. - Avoid raw
page.waitForTimeout(): Fixed sleeps slow down passing tests and still fail when CI CPU spikes. Web-first assertions such asawait expect(locator).toBeVisible()poll automatically until the condition passes or times out. - Keep every test completely isolated: Never rely on state left behind by a previous test case, because parallel workers and retries execute tests in arbitrary order.
If you use AI assistants to scaffold initial test files, run every generated spec through a rigorous quality check before merging. Our guide on How to Review AI-Generated Code: A Practical Checklist covers common hallucinations like fragile selectors and missing assertions.
Isolating Auth State and Network Mocks Between Test Cases
Logging in through the UI before every single test wastes minutes of CI time. Instead, Playwright lets you authenticate once in a setup project, save cookies and localStorage with storageState, and reuse that authenticated browser state across isolated test contexts, while mocking flaky third-party webhooks via page.route().
Reusing Authenticated Sessions Safely with storageState
Define a dedicated tests/e2e/auth.setup.ts file that signs in once against your test account and writes the resulting session state to playwright/.auth/user.json (git-ignored). Every browser project that depends on the setup project loads that file into a fresh browser context, meaning tests start authenticated in milliseconds without sharing mutable cookies or DOM state across workers.
typescriptimport { test as setup, expect } from "@playwright/test";
const authFile = "playwright/.auth/user.json";
setup("authenticate test user", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Email").fill(process.env.E2E_USER_EMAIL ?? "[email protected]");
await page.getByLabel("Password").fill(process.env.E2E_USER_PASSWORD ?? "test-password");
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
await page.context().storageState({ path: authFile });
});
Keep your network interception rules scoped directly inside individual test functions rather than globally across files. In the example below, page.route() intercepts a quota endpoint inside a single test case so the suite never depends on external billing sandboxes.
typescriptimport { test, expect } from "@playwright/test";
test.describe("Project dashboard", () => {
test("creates a deployment token and renders masked secret", async ({ page }) => {
// Stub external billing endpoint so tests never hit third-party sandboxes
await page.route("**/api/billing/quota", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ remainingTokens: 5, plan: "pro" }),
});
});
await page.goto("/settings/tokens");
await page.getByRole("button", { name: "New API token" }).click();
await page.getByLabel("Token name").fill("ci-deploy-runner");
await page.getByRole("button", { name: "Create token" }).click();
const dialog = page.getByRole("dialog", { name: "Token created" });
await expect(dialog).toBeVisible();
await expect(dialog.getByText("ci-deploy-runner")).toBeVisible();
});
});
Running Playwright in GitHub Actions with Sharding and HTML Reports
As documented in Playwright Setting up CI, Playwright generates a ready-to-use GitHub Actions workflow that runs tests on pushes and pull requests and uploads HTML reports as workflow artifacts. When your test count grows, add matrix sharding (--shard=1/4) so four runners execute your browser matrix in parallel.

yamlname: Playwright E2E
on:
push:
branches: [main]
pull_request:
jobs:
e2e:
timeout-minutes: 20
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
shardIndex: [1, 2]
shardTotal: [2]
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
- run: npm run build
- run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-report-${{ matrix.shardIndex }}
path: playwright-report/
retention-days: 14
Once your CI suite passes reliably on every pull request, you can gate production releases directly in the same pipeline. See GitHub Actions Deploy to VPS: Secure SSH Pipeline Step by Step to chain green E2E checks into automated server deployments.
Debugging CI Failures Quickly with Playwright Trace Viewer
Reading a stack trace from a headless CI failure rarely tells you why a button was obscured by a toast notification or why an API call returned 401. Because we configured trace: "on-first-retry" in playwright.config.ts, Playwright records a full trace archive (trace.zip) whenever a failing test is retried.
| Artifact or Tool | When It Triggers | What It Reveals |
|---|---|---|
| HTML Report | Every CI run | Pass/fail summary across browsers, retries, and shard timings |
| Trace Viewer (trace.zip) | On first retry of failed test | DOM snapshots per action, network waterfall, console logs, and source lines |
| UI Mode (–ui) | Local development | Interactive watch mode with live time-travel step inspection |
| Codegen (playwright codegen) | Local authoring | Generates role-based locators directly from browser clicks |
Download the uploaded report artifact from GitHub Actions, unzip it locally, and launch the interactive viewer with one command to scrub through every DOM frame, network payload, and console error from the exact moment the assertion failed.
bash# Open the downloaded HTML report or inspect a trace zip directly
npx playwright show-report ./playwright-report-1
npx playwright show-trace ./test-results/tokens-retry1/trace.zip
By combining role-based locators, auto-retrying assertions, isolated test state, CI sharding, and trace-on-retry artifacts, your Playwright TypeScript suite stays fast, deterministic, and easy to diagnose whenever a real regression slips into a pull request.