Playwright
Core Workflow
- Analyze - Identify user flows and test scope
- Configure - Set up
playwright.config.ts (see references/configuration.md)
- Write tests - Use proper locators, auto-waiting, and assertions
- Organize - Apply fixtures, POM, parallelism (see references/test-organization.md)
- Debug - Use traces, UI mode (see references/debugging.md)
Reference Guide
Load based on context:
| Topic |
Reference |
Load When |
| Locators & Actions |
references/locators-and-actions.md |
Writing selectors, filling forms, clicking, drag-and-drop |
| Test Organization |
references/test-organization.md |
Fixtures, parallel execution, retries, sharding, timeouts, annotations |
| Authentication |
references/authentication.md |
Login flows, multi-role tests, storageState |
| Network & Mocking |
references/network-and-mocking.md |
API mocking, route interception, HAR recording, API testing |
| Visual Testing |
references/visual-testing.md |
Screenshots, snapshots, ARIA snapshots, visual regression |
| Debugging |
references/debugging.md |
Flaky tests, trace viewer, UI mode, debug flags |
| Configuration |
references/configuration.md |
playwright.config.ts, projects, web server, CI/CD, reporters |
| Advanced |
references/advanced.md |
Clock mocking, evaluate, component testing, POM, accessibility |
Critical Rules
MUST DO
- Use
getByRole() > getByLabel() > getByTestId() > getByText() (in priority order)
- Use web-first assertions:
await expect(locator).toBeVisible() (auto-retries)
- Keep tests independent - no shared mutable state between tests
- Enable
trace: 'on-first-retry' for debugging failures
- Use
fullyParallel: true for speed
- Use
forbidOnly: !!process.env.CI to prevent .only leaking to CI
MUST NOT
- Use
waitForTimeout() — always use proper auto-waiting assertions
- Use CSS class selectors — they break on refactors
- Use
expect(await locator.isVisible()).toBe(true) — this does NOT auto-retry; use await expect(locator).toBeVisible() instead
- Share state between tests (each test gets a fresh
BrowserContext)
- Use
first()/nth() without narrowing first — filter or chain locators instead
Common Gotchas
- Assertion retrying: Only
expect(locator) retries. expect(await locator.something()) evaluates once.
has-text pseudo-class: Without another CSS specifier, matches everything including <body>. Always combine with an element selector.
getByText whitespace: Always normalizes whitespace, even with exact: true.
opacity: 0: Considered visible. Zero-size elements are NOT visible.
- Shadow DOM: All locators pierce Shadow DOM by default EXCEPT XPath.
fill() actionability: Checks Visible + Enabled + Editable only. Does NOT check Stable or Receives Events.
press()/pressSequentially(): NO actionability checks at all.
- Dialogs: Listener MUST handle (accept/dismiss) the dialog or the page action will stall permanently.
storageState: Covers cookies, localStorage, IndexedDB. Does NOT cover sessionStorage.
- TypeScript: Playwright does NOT type-check — it only transpiles. Run
tsc separately.
expect.toPass timeout: Defaults to 0 (no retry), NOT the expect timeout.
- Glob patterns:
* does not match /. ** matches everything. ? matches literal ? only.
- Serial mode retries: Retries ALL tests in the group, not just the failed one.
- Worker shutdown: Worker processes are always killed after a test failure.
- Drag events: For
dragover to fire in all browsers, issue TWO mouse.move() calls.
- Videos: Only available AFTER page/context is closed.
Quick Setup
# New project
npm init playwright@latest
# Existing project
npm i -D @playwright/test
npx playwright install
Minimal Config
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost: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'] } },
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
});
Minimal Test
import { test, expect } from '@playwright/test';
test('homepage has title', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/My App/);
await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
});
CLI Quick Reference
npx playwright test # Run all
npx playwright test auth.spec.ts # Run file
npx playwright test --grep @smoke # Run tagged
npx playwright test --project=chromium # Single browser
npx playwright test --debug # Debug mode (headed, timeout=0, workers=1)
npx playwright test --ui # UI mode
npx playwright show-report # HTML report
npx playwright show-trace trace.zip # View trace
npx playwright codegen localhost:3000 # Generate tests
1---2name: playwright3description: Write, debug, and maintain Playwright end-to-end tests for web applications. Use when working with Playwright test files, configuring playwright.config.ts, writing browser automation, debugging flaky E2E tests, setting up authentication for tests, API mocking/interception, visual regression testing, accessibility testing, or CI/CD integration for browser tests. Triggers: Playwright, E2E test, end-to-end, browser test, @playwright/test, playwright.config, page object model, test fixture, visual snapshot, trace viewer.4---56# Playwright78## Core Workflow9101. **Analyze** - Identify user flows and test scope112. **Configure** - Set up `playwright.config.ts` (see [references/configuration.md](references/configuration.md))123. **Write tests** - Use proper locators, auto-waiting, and assertions134. **Organize** - Apply fixtures, POM, parallelism (see [references/test-organization.md](references/test-organization.md))145. **Debug** - Use traces, UI mode (see [references/debugging.md](references/debugging.md))1516## Reference Guide1718Load based on context:1920| Topic | Reference | Load When |21|-------|-----------|-----------|22| Locators & Actions | [references/locators-and-actions.md](references/locators-and-actions.md) | Writing selectors, filling forms, clicking, drag-and-drop |23| Test Organization | [references/test-organization.md](references/test-organization.md) | Fixtures, parallel execution, retries, sharding, timeouts, annotations |24| Authentication | [references/authentication.md](references/authentication.md) | Login flows, multi-role tests, storageState |25| Network & Mocking | [references/network-and-mocking.md](references/network-and-mocking.md) | API mocking, route interception, HAR recording, API testing |26| Visual Testing | [references/visual-testing.md](references/visual-testing.md) | Screenshots, snapshots, ARIA snapshots, visual regression |27| Debugging | [references/debugging.md](references/debugging.md) | Flaky tests, trace viewer, UI mode, debug flags |28| Configuration | [references/configuration.md](references/configuration.md) | playwright.config.ts, projects, web server, CI/CD, reporters |29| Advanced | [references/advanced.md](references/advanced.md) | Clock mocking, evaluate, component testing, POM, accessibility |3031## Critical Rules3233### MUST DO34- Use `getByRole()` > `getByLabel()` > `getByTestId()` > `getByText()` (in priority order)35- Use web-first assertions: `await expect(locator).toBeVisible()` (auto-retries)36- Keep tests independent - no shared mutable state between tests37- Enable `trace: 'on-first-retry'` for debugging failures38- Use `fullyParallel: true` for speed39- Use `forbidOnly: !!process.env.CI` to prevent `.only` leaking to CI4041### MUST NOT42- Use `waitForTimeout()` — always use proper auto-waiting assertions43- Use CSS class selectors — they break on refactors44- Use `expect(await locator.isVisible()).toBe(true)` — this does NOT auto-retry; use `await expect(locator).toBeVisible()` instead45- Share state between tests (each test gets a fresh `BrowserContext`)46- Use `first()`/`nth()` without narrowing first — filter or chain locators instead4748## Common Gotchas49501. **Assertion retrying**: Only `expect(locator)` retries. `expect(await locator.something())` evaluates once.512. **`has-text` pseudo-class**: Without another CSS specifier, matches everything including `<body>`. Always combine with an element selector.523. **`getByText` whitespace**: Always normalizes whitespace, even with `exact: true`.534. **`opacity: 0`**: Considered visible. Zero-size elements are NOT visible.545. **Shadow DOM**: All locators pierce Shadow DOM by default EXCEPT XPath.556. **`fill()` actionability**: Checks Visible + Enabled + Editable only. Does NOT check Stable or Receives Events.567. **`press()`/`pressSequentially()`**: NO actionability checks at all.578. **Dialogs**: Listener MUST handle (accept/dismiss) the dialog or the page action will stall permanently.589. **`storageState`**: Covers cookies, localStorage, IndexedDB. Does NOT cover sessionStorage.5910. **TypeScript**: Playwright does NOT type-check — it only transpiles. Run `tsc` separately.6011. **`expect.toPass` timeout**: Defaults to `0` (no retry), NOT the expect timeout.6112. **Glob patterns**: `*` does not match `/`. `**` matches everything. `?` matches literal `?` only.6213. **Serial mode retries**: Retries ALL tests in the group, not just the failed one.6314. **Worker shutdown**: Worker processes are always killed after a test failure.6415. **Drag events**: For `dragover` to fire in all browsers, issue TWO `mouse.move()` calls.6516. **Videos**: Only available AFTER page/context is closed.6667## Quick Setup6869```bash70# New project71npm init playwright@latest7273# Existing project74npm i -D @playwright/test75npx playwright install76```7778### Minimal Config7980```typescript81import { defineConfig, devices } from '@playwright/test';8283export default defineConfig({84 testDir: './e2e',85 fullyParallel: true,86 forbidOnly: !!process.env.CI,87 retries: process.env.CI ? 2 : 0,88 workers: process.env.CI ? 1 : undefined,89 reporter: 'html',90 use: {91 baseURL: 'http://localhost:3000',92 trace: 'on-first-retry',93 screenshot: 'only-on-failure',94 },95 projects: [96 { name: 'chromium', use: { ...devices['Desktop Chrome'] } },97 { name: 'firefox', use: { ...devices['Desktop Firefox'] } },98 { name: 'webkit', use: { ...devices['Desktop Safari'] } },99 ],100 webServer: {101 command: 'npm run dev',102 url: 'http://localhost:3000',103 reuseExistingServer: !process.env.CI,104 },105});106```107108### Minimal Test109110```typescript111import { test, expect } from '@playwright/test';112113test('homepage has title', async ({ page }) => {114 await page.goto('/');115 await expect(page).toHaveTitle(/My App/);116 await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();117});118```119120## CLI Quick Reference121122```bash123npx playwright test # Run all124npx playwright test auth.spec.ts # Run file125npx playwright test --grep @smoke # Run tagged126npx playwright test --project=chromium # Single browser127npx playwright test --debug # Debug mode (headed, timeout=0, workers=1)128npx playwright test --ui # UI mode129npx playwright show-report # HTML report130npx playwright show-trace trace.zip # View trace131npx playwright codegen localhost:3000 # Generate tests132```