Playwright Reference
Free reference guide: Playwright Reference
About Playwright Reference
The Playwright Reference is a comprehensive cheat sheet for end-to-end testing with Microsoft Playwright. It covers eight key areas: semantic locators (getByRole, getByText, getByLabel, getByPlaceholder, getByTestId, locator with CSS/XPath, filter, and nth), interaction actions (goto, click, fill, type, press, check, selectOption, hover, dblclick), expect-based assertions (toBeVisible, toHaveText, toHaveValue, toHaveCount, toBeEnabled, toHaveClass, toHaveURL, toHaveTitle), page lifecycle methods (waitForSelector, waitForURL, waitForLoadState, evaluate, reload, goBack), network interception (route, abort, waitForResponse, waitForRequest, continue with header modification), screenshot and visual regression testing (page/element screenshots, toHaveScreenshot for visual diffing, PDF generation), configuration (playwright.config.ts, projects for multi-browser, globalSetup), and CLI commands.
This reference is most useful for frontend developers and QA engineers writing Playwright tests, teams migrating from Selenium or Cypress who need to learn Playwright's locator API, and developers who need a quick reminder for the exact assertion method name or how to intercept an API call in a test. Playwright's modern locator API uses accessibility semantics (role, label, text) rather than brittle CSS selectors, making tests more maintainable.
The reference is organized to match a typical test authoring workflow: find the element using a semantic locator, interact with it using an action, assert the expected outcome using expect(), and handle asynchronous behavior with Playwright's built-in auto-waiting. Advanced patterns like network mocking with route.fulfill() and visual regression with toHaveScreenshot() are grouped in dedicated sections for easy lookup.
Key Features
- Semantic locators: getByRole, getByText, getByLabel, getByPlaceholder, getByTestId
- CSS/XPath locators with locator(), locator.filter() for chaining, and locator.nth() for nth element
- Interaction actions: goto, click, fill, type with delay, press, check, selectOption, hover, dblclick
- Expect assertions: toBeVisible, toHaveText, toHaveValue, toHaveCount, toBeEnabled, toHaveClass
- Page-level assertions: toHaveURL and toHaveTitle for navigation verification
- Network interception: route.fulfill() to mock APIs, route.abort() to block requests, route.continue() to modify headers
- Visual regression testing with toHaveScreenshot(), element screenshots, and PDF generation
- CLI commands: npx playwright test, --ui mode, codegen recorder, show-report, and --debug mode
Frequently Asked Questions
What is the difference between getByRole and locator in Playwright?
`getByRole()` finds elements by their ARIA role and accessible name, which makes tests resilient to DOM structure changes and aligned with accessibility standards. For example, `getByRole("button", { name: "Submit" })` finds a button regardless of its CSS class or position. `locator()` accepts CSS selectors and XPath expressions, which are more powerful for complex DOM queries but more fragile. Prefer `getByRole`, `getByText`, and `getByLabel` over CSS selectors when possible.
How does Playwright auto-wait work and when do I need waitForSelector?
Playwright automatically waits for elements to be actionable before performing interactions — it waits for the element to be visible, not disabled, and not covered by another element. This means most tests do not need explicit wait calls. Use `page.waitForSelector()` or `page.waitForURL()` when you need to wait for a specific condition that is not part of an action, such as waiting for a loading spinner to disappear before asserting.
How do I mock an API response in a Playwright test?
Use `page.route(pattern, handler)` to intercept requests matching a URL pattern. In the handler, call `route.fulfill({ status: 200, body: JSON.stringify(data) })` to return a mock response. Use `route.abort()` to block requests (e.g., blocking image loads to speed up tests). Use `route.continue({ headers: { ...route.request().headers(), "X-Test": "true" } })` to modify request headers before forwarding.
What is the difference between locator.fill() and locator.type()?
`locator.fill()` clears the input field and sets the entire value at once — it is fast and is the recommended method for filling form inputs. `locator.type()` simulates actual keystroke-by-keystroke keyboard input with an optional `delay` between keystrokes, which is useful for testing typeahead or autocomplete components that listen to individual key events. For most form filling, use `fill()` for speed.
How do I run Playwright tests against multiple browsers?
Configure `projects` in `playwright.config.ts` to specify browser targets: `{ name: "chromium", use: { ...devices["Desktop Chrome"] } }`. You can add separate project entries for Firefox and Safari. Run all browsers with `npx playwright test`, or target a specific project with `npx playwright test --project=chromium`. The `devices` map from `@playwright/test` provides realistic viewport and user agent configurations for both desktop and mobile devices.
How does visual regression testing work with toHaveScreenshot()?
`await expect(page).toHaveScreenshot("homepage.png")` captures a screenshot and compares it against a stored baseline image. On first run, the baseline is created. On subsequent runs, any pixel differences beyond a configurable threshold cause the test to fail. Update baselines with `npx playwright test --update-snapshots`. You can also snapshot individual elements: `await expect(page.locator(".header")).toHaveScreenshot()` for component-level visual regression.
How do I use Playwright Codegen to record tests?
Run `npx playwright codegen https://example.com` to open a browser with a recording panel. Every interaction you perform (clicks, form fills, navigation) is automatically translated into Playwright test code in real time. The generated code uses the recommended locator APIs. You can also record authenticated sessions by passing `--save-storage=auth.json` to save cookies and localStorage, which can then be loaded in tests.
How do I debug a failing Playwright test?
Run `npx playwright test --debug tests/login.spec.ts` to open Playwright Inspector, which pauses before each action and lets you step through the test. You can also add `await page.pause()` at any point in your test to pause execution. The `--ui` flag opens the full Playwright UI with a timeline, network log, and snapshot viewer. For CI failures, use `page.screenshot()` in a catch block and `npx playwright show-report` to view the HTML report with traces.