Playwright E2E Testing Cheat Sheet
Quick reference guide for Playwright: Locators, page actions, assertions, fixtures, and CLI runner.
Testing
playwright
e2e
testing
Playwright enables reliable end-to-end (E2E) testing for modern web apps across Chromium, Firefox, and WebKit browsers.
Recommended Locators API
Playwright recommends user-facing locators that remain resilient against DOM structure changes.
Table
| Locator | Best Use Case | Example Syntax |
|---|---|---|
page.getByRole(role, { name }) | Buttons, links, headings, checkboxes | page.getByRole('button', { name: 'Submit' }) |
page.getByLabel(text) | Form inputs associated with <label> | page.getByLabel('Email Address') |
page.getByPlaceholder(text) | Inputs with placeholder attribute | page.getByPlaceholder('Search...') |
page.getByTestId(id) | Fallback explicitly tagged data-testid | page.getByTestId('submit-btn') |
page.getByText(text) | Non-interactive text content | page.getByText('Welcome back') |
E2E Test Spec Example
typescript
import { test, expect } from "@playwright/test";
test.describe("Authentication Flow", () => {
test.beforeEach(async ({ page }) => {
await page.goto("/login");
});
test("user can log in successfully", async ({ page }) => {
// Fill credentials
await page.getByLabel("Email").fill("user@example.com");
await page.getByLabel("Password").fill("secret123");
// Click submit button
await page.getByRole("button", { name: "Sign In" }).click();
// Verify URL redirect & welcome heading
await expect(page).toHaveURL("/dashboard");
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Dashboard");
});
});
Essential Playwright CLI Commands
Table
| Command | Action / Purpose |
|---|---|
npx playwright test | Run all end-to-end tests headless |
npx playwright test --ui | Open interactive visual Playwright UI mode |
npx playwright test --headed | Run tests with browser UI window visible |
npx playwright codegen http://localhost:3000 | Open browser recorder to auto-generate test scripts |
npx playwright show-report | Serve HTML test execution report in browser |
Common Pitfalls & Tips
[!WARNING] Avoid legacy XPath or CSS selectors like
page.locator('div > ul > li:nth-child(2)'); fragile DOM selectors break frequently when CSS styles or layouts update!
[!TIP] Playwright automatically waits for elements to become visible, enabled, and stable before performing actions like
click()orfill().