Playwright E2E Testing Patterns
Quick Guide: Use Playwright for end-to-end tests that verify complete user workflows through the real browser. Focus on critical user journeys, use accessibility-based locators (getByRole), and leverage auto-waiting assertions -- never use manual sleeps. Isolate each test with its own browser context. Mock external APIs via route interception for reliability.
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)
(You MUST use getByRole() as your primary locator strategy - it mirrors how users interact with the page)
(You MUST test complete user workflows end-to-end - login flows, checkout processes, form submissions)
(You MUST use web-first assertions that auto-wait - toBeVisible(), toHaveText(), not manual sleeps)
(You MUST isolate tests - each test runs independently with its own browser context)
(You MUST use named constants for test data - no magic strings or numbers in test files)
</critical_requirements>
Auto-detection: Playwright, E2E testing, end-to-end testing, browser automation, page.goto, test.describe, expect(page), getByRole, getByTestId, toBeVisible, toHaveScreenshot, toMatchAriaSnapshot
When to use:
- Testing critical user-facing workflows (login, checkout, form submission)
- Multi-step user journeys that span multiple pages
- Cross-browser compatibility testing
- Testing real integration with backend APIs
- Visual regression testing with screenshots
- Accessibility tree validation with ARIA snapshots
When NOT to use:
- Testing pure utility functions (use unit tests)
- Testing individual component variants in isolation (use component testing tools)
- API-only testing without UI (use API testing)
Key patterns covered:
- Test structure and organization (test.describe, test, hooks)
- Page Object Model pattern for maintainability
- Locator strategies prioritizing accessibility (getByRole, getByLabel, chaining, operators)
- Web-first assertions with auto-waiting (toBeVisible, toHaveText, soft assertions)
- Network mocking and interception (route.fulfill, route.abort, response modification)
- Visual regression testing (toHaveScreenshot, masking, thresholds)
- Custom and worker-scoped fixtures
- Clock API for time-dependent testing (v1.45+)
- ARIA snapshot testing for accessibility (v1.49+)
- Accessibility assertions (v1.44+): toHaveAccessibleName, toHaveRole
Detailed Resources:
- [examples/core.md](examples/core.md) - User flows, page objects, network mocking, config, auth fixtures
- [examples/page-objects.md](examples/page-objects.md) - Base page inheritance, hierarchy
- [examples/api-mocking.md](examples/api-mocking.md) - Response interception and modification
- [examples/visual-testing.md](examples/visual-testing.md) - Screenshot comparison, component visual testing
- [examples/fixtures.md](examples/fixtures.md) - Combined fixtures, database seeding, IndexedDB state
- [examples/advanced-features.md](examples/advanced-features.md) - Clock API, ARIA snapshots, worker fixtures, polling assertions, accessibility assertions
- [reference.md](reference.md) - Decision frameworks, locator/assertion tables, anti-patterns, CLI commands, configuration reference
<philosophy>
Philosophy
Playwright E2E tests verify that your application works correctly from the user's perspective. They interact with the real browser, navigate through actual pages, and validate user-visible behavior.
Core Principles:
- Test user-visible behavior - Focus on what end users see and interact with, not implementation details
- Use accessibility locators -
getByRolemirrors how screen readers and users interact with pages - Isolate tests completely - Each test has its own browser context, cookies, and storage
- Trust auto-waiting - Playwright automatically waits for elements; no manual sleeps needed
- Mock external dependencies - Use route interception for third-party APIs to ensure reliability
When E2E tests provide the most value:
- Critical business workflows (authentication, payments, core features)
- User journeys spanning multiple pages or components
- Testing real backend integration
- Cross-browser compatibility verification
- Catching integration bugs that unit tests miss
When E2E tests may not be the best choice:
- Testing pure utility functions (unit tests are faster and more precise)
- Testing component styling variants (use visual testing tools)
- Testing every edge case (balance with unit and integration tests)
</philosophy>
<patterns>
Core Patterns
Pattern 1: Test Structure and Organization
Group related tests with test.describe, use beforeEach for common navigation, and name constants for all test data.
const LOGIN_URL = "/login";
const VALID_EMAIL = "user@example.com";
test.describe("Login Flow", () => {
test.beforeEach(async ({ page }) => {
await page.goto(LOGIN_URL);
});
test("successful login redirects to dashboard", async ({ page }) => {
await page.getByLabel(/email/i).fill(VALID_EMAIL);
// ... fill password, click sign in
await expect(page).toHaveURL("/dashboard");
});
});
Why good: Groups related tests logically, beforeEach maintains isolation, named constants prevent magic strings
See [examples/core.md](examples/core.md) Pattern 1 for complete user flow with error scenarios.
Pattern 2: Page Object Model
Encapsulate page structure and interactions in reusable classes. Define locators in the constructor, expose domain-specific methods.
export class LoginPage {
readonly emailInput: Locator;
readonly signInButton: Locator;
constructor(page: Page) {
this.emailInput = page.getByLabel(/email/i);
this.signInButton = page.getByRole("button", { name: /sign in/i });
}
async login(email: string, password: string) {
await this.emailInput.fill(email);
// ...
}
}
Why good: Centralizes locators -- UI changes update one place, methods encapsulate interactions
When to use: Tests spanning multiple interactions on the same page, reusable flows across test files.
When not to use: Simple one-off tests where inline locators are clearer.
See [examples/core.md](examples/core.md) Pattern 2 for full page objects with fixtures, [examples/page-objects.md](examples/page-objects.md) for base page inheritance.
Pattern 3: Locator Strategies
Prioritize accessibility-based locators that mirror how users interact with the application.
// BEST: Accessibility-based
await page.getByRole("button", { name: /submit/i });
await page.getByLabel(/email address/i);
await page.getByText(/welcome back/i);
// ACCEPTABLE: Test IDs for complex cases
await page.getByTestId("user-avatar"); // When no semantic role exists
// AVOID: Implementation-dependent
await page.locator("#submit-btn"); // Fragile
await page.locator(".btn-primary"); // CSS class can change
Chaining and filtering narrow down to specific elements without fragile selectors:
await page
.getByRole("listitem")
.filter({ hasText: "Product A" })
.getByRole("button", { name: /add to cart/i })
.click();
// Exclude elements (v1.33+)
await page
.getByRole("listitem")
.filter({ hasNot: page.getByText("Out of stock") })
.first()
.click();
// Combine conditions (v1.33+)
const btn = page.getByRole("button").and(page.getByTitle("Subscribe"));
Why good: getByRole validates accessibility as a side effect, survives UI refactoring, chaining handles dynamic lists
See [reference.md](reference.md) for locator priority table and common ARIA role mappings.
Pattern 4: Web-First Assertions
Use assertions that automatically wait and retry until the condition is met.
// Auto-waits for element visibility