playwright-best-practices-for-agents
Playwright best practices
Condensed, opinionated guidance for writing Playwright tests that are readable, isolated, and resilient — built for coding agents, around Playwright's agent CLI (playwright-cli) and its no-GUI debugging flows. Maintained by Checkly — the same practices apply whether you run these tests in CI or as production monitors.
Load a reference file from references/ only when the task needs it (see routing table). Each reference ends with links to the full /learn articles for depth.
Scope: all guidance assumes the
@playwright/testtest runner with TypeScript — itstest, fixtures, projects, config, and web-firstexpect. Examples are TypeScript (.spec.ts); the same APIs work in JavaScript. It does not target the standaloneplaywrightautomation library (which has no test runner, fixtures, or auto-retrying assertions). Imports areimport { test, expect } from '@playwright/test'.
The agent CLI is what makes this skill shine. Playwright's agent CLI —
playwright-cli, package@playwright/cli— is a separate, token-efficient, no-GUI browser you drive command by command to discover locators and step through failing tests. It's distinct from the standardnpx playwrightCLI, and the Agentic workflow below leans on it throughout. → references/debugging.md
Core rules (always apply)
- Locator priority: prefer user-facing locators —
getByRole>getByLabel/getByPlaceholder/getByText>getByTestId> CSS/XPath. CSS/XPath tie tests to implementation and break easily. → references/locators.md - Web-first assertions: use auto-retrying
expect(locator).toBeVisible()/toHaveText()etc. Never assert on a one-shot value you pulled out manually (innerText()thentoBe). → references/assertions.md - No hard waits: never
waitForTimeout(). Trust auto-waiting actions and web-first assertions; for explicit waits usewaitForURL/waitForLoadState/waitForResponse. Avoidnetworkidle. → references/waiting.md - Isolated & independent: each test sets up its own state and can run in any order, in parallel. No test depends on another. Provision state via API in setup, not through the UI. → references/test-structure.md, references/flakiness.md
- One feature per test: if a test's assertions span more than one feature, split it. Keep tests short and focused.
- Reuse auth, don't re-login: sign in once, persist
storageState, reuse it across tests via a setup project. → references/auth.md