Advanced Testing Patterns
End-to-End Testing with Playwright
Automate real browser testing with Playwright — the modern E2E framework with auto-wait and cross-browser support.
Why Playwright
Playwright is the recommended E2E testing framework for modern web applications:
- Cross-browser — Chromium, Firefox, and WebKit (Safari) in one framework
- Auto-wait — Playwright automatically waits for elements to be ready before interacting
- Fast — Tests run in parallel by default
- TypeScript-native — Full type safety
- Trace viewer — Debug failures by recording and replaying test execution
Installation
Install with npm init playwright@latest. This creates playwright.config.ts and an example test.
Locator Strategies
Use locators in this priority order:
- getByRole (most semantic)
- getByLabel (great for form inputs)
- getByText (visible text)
- getByPlaceholder
- getByTestId (last resort)
Page Object Model
For maintainable E2E tests, encapsulate page interactions in Page Object classes. Each page class has methods for the page's key user actions. Tests use these methods rather than raw locators.
Authentication State Reuse
Save login state once to a JSON file using storageState, then reuse it across tests. This dramatically speeds up test suites by avoiding repeated logins.
Key Takeaways
- Playwright auto-waits for elements to be actionable — no manual sleep() calls needed
- Use semantic locators (getByRole, getByLabel) over CSS selectors — they match what users see
- The Page Object Model (POM) encapsulates page interactions — DRY, maintainable tests
- Save authenticated state once and reuse across tests — dramatically speeds up test suites
- Run in CI with headless mode; use the trace viewer locally to debug failures
Example
typescript
// Complete E2E test for a checkout flowTry it yourself — TYPESCRIPT