Playwright Cheatsheet: Commands, Locators, Assertions, and Config for 2026
Every Playwright command, locator, assertion, and config option in one verified 2026 cheatsheet, plus the deprecated APIs to replace.

Playwright shipped 2 releases in 33 days this autumn, and the @playwright/test package pulled over 260 million downloads in September 2026 alone, according to the npm registry downloads API. Most Playwright cheatsheets online still open with page.click('#submit') and page.waitForSelector(), which the official docs stopped recommending years ago.
Copying from a stale Playwright cheat sheet has a real cost. A test built on element handles and hard waits passes locally, then fails in CI the first time a spinner takes 600 milliseconds longer. That failure gets a retry, the retry gets a "flaky" label, and the label never leaves.
This Playwright cheatsheet is verified against Playwright 1.64, the October 2026 release. Every table is copy-ready, every snippet uses the test runner, and the last section lists the old APIs you should replace, along with their current equivalents.
What is a Playwright cheatsheet, and why the one you bookmarked is stale
Definition: A Playwright cheatsheet is a single-page quick reference of the commands, locators, actions, assertions, and configuration options used most often when writing Playwright tests. This one covers the @playwright/test runner in TypeScript, is verified against Playwright 1.64, and uses web-first assertions and locators throughout.
The sections follow the order you meet them in a real project: install and run, find an element, act on it, assert, organise tests, configure the runner, mock the network, sign in, debug, and hand the suite to an AI agent. If you are starting from zero, the learn Playwright roadmap explains the concepts in order, and this Playwright cheatsheet is the reference you keep open afterwards.
Most of the staleness in older cheatsheets comes from one shift. Since the locator API arrived, the recommended way to interact with a page is locator → action with auto-waiting, not wait → find → act. Everything else on this page builds on that.
What changed since Playwright 1.60
The table below is the list of additions you are least likely to find in a Playwright cheat sheet written before mid-2026. Each one is taken from the official release notes and appears again in the section where it belongs.
| Version | Addition | Syntax |
|---|---|---|
| 1.60 | Abort a test from a fixture or hook; file drops; HAR from tracing | test.abort(), locator.drop(), tracing.startHar() |
| 1.61 | Web storage objects; grep-invert shorthand; soft polling | page.localStorage.getItem(), -G, expect.soft.poll |
| 1.62 | Isolated retries; WebP screenshots; MCP and CLI bundled | retryStrategy: 'isolated', type: 'webp', npx playwright mcp |
| 1.63 | Named test locks; visible-only locators; cross-frame search | { lock: 'name' }, locator.visible(), frameLocator() |
| 1.64 | Reversed scoping; ref locators; shuffled runs; default projects | locator.within(), page.getByRef(), --shuffle, default: false |
Playwright publishes a new minor version roughly every 4 to 6 weeks. TestDino's Playwright release notes hub tracks each one in plain language, which is how this cheatsheet gets refreshed.

Playwright setup and CLI commands cheatsheet
One command scaffolds a working project. The wizard asks for TypeScript or JavaScript, a tests folder, a GitHub Actions workflow, and whether to download browsers.
npm init playwright@latest
# Creates playwright.config.ts, package.json, and tests/example.spec.ts
npx playwright --version
# Version 1.64.0
Playwright 1.64 requires Node.js 22, 24, or 26 and supports Windows 11, macOS 14, Debian 12 and 13, and Ubuntu 22.04 to 26.04. Older cheatsheets that mention Node 12 or npm i -D playwright describe the library without the test runner, which is not what you want for end-to-end tests.
Updating is 2 commands, and the second one matters more than it looks. Browser builds change with every release, so install --with-deps keeps the engines in sync with the package.
npm install -D @playwright/test@latest
npx playwright install --with-deps
The npx playwright test flags you will actually use
Every flag in this part of the Playwright cheatsheet comes from the current test CLI reference. The ones added recently are marked with their version.
| Command | What it does |
|---|---|
| npx playwright test | Run every test in every project |
| npx playwright test tests/login.spec.ts | Run 1 file; the argument is a regex against file paths |
| npx playwright test -g "checkout" | Run tests whose title matches a regex |
| npx playwright test -G "@slow" | Skip tests whose title matches (shorthand for --grep-invert, 1.61) |
| npx playwright test --project=chromium | Run 1 project; wildcards like --project="*" work |
| npx playwright test --headed | Show the browser window |
| npx playwright test --ui | Open UI mode with watch, time travel, and a locator picker |
| npx playwright test --debug | Open the Inspector; implies --headed, --workers=1, --timeout=0 |
| npx playwright test --debug=cli | Pause for an AI agent attached through playwright-cli (1.59) |
| npx playwright test --last-failed | Rerun only the tests that failed last time |
| npx playwright test --only-changed | Run only files changed in git since the last commit |
| npx playwright test --repeat-each 10 -g "cart" | Run matching tests 10 times to expose flakiness |
| npx playwright test --shuffle | Randomise order and print a seed; pass the seed to replay (1.64) |
| npx playwright test --retries 2 | Retry failures up to 2 times |
| npx playwright test --workers 4 | Set worker count; accepts a percentage like 50% |
| npx playwright test --shard 1/4 | Run the first of 4 shards |
| npx playwright test --trace on | Record a trace for every test |
| npx playwright test --reporter=line,html | Replace the configured reporters |
| npx playwright test --add-reporter json | Add a reporter without replacing the config (1.63) |
| npx playwright test -u | Update changed snapshots; -u missing only adds new ones |
| npx playwright test --list | Print the tests that would run, without running them |
| npx playwright test -x | Stop after the first failure; --max-failures 5 for a limit |
| npx playwright test --forbid-only --fail-on-flaky-tests | CI guards against a stray test.only and against flaky passes |
| npx playwright test --timeout 60000 --global-timeout 1800000 | Per-test and whole-run limits in milliseconds |
The -g flag takes a JavaScript regular expression, which trips people up on Windows. In PowerShell, quote the pattern and escape the pipe, so --grep "@fast|@slow" becomes --grep --% "@fast^|@slow". The Playwright Regex Tester lets you check a pattern against your test titles before you run anything.
Subcommands beyond test
Beyond test, the same binary records tests, serves reports, and manages browsers.
| Command | What it does |
|---|---|
| npx playwright codegen https://storedemo.testdino.com -o tests/recorded.spec.ts | Record actions into a spec; add --target playwright-test, --device "iPhone 15", or --test-id-attribute data-qa |
| npx playwright show-report | Serve the last HTML report on port 9323 |
| npx playwright show-trace test-results/login-chromium/trace.zip | Open a trace file in the trace viewer |
| npx playwright install chromium | Install 1 browser; --with-deps adds OS packages, --no-remove keeps old builds (1.63) |
| npx playwright install-deps --dry-run | Print the system packages a Linux image needs |
| npx playwright merge-reports --reporter html ./blob-reports | Combine blob reports from shards into 1 HTML report |
| npx playwright clear-cache | Delete cached browser downloads and compiled files |
| npx playwright init-agents --loop=claude | Generate planner, generator, and healer agent definitions (also vscode, codex, opencode) |
| npx playwright mcp | Start the bundled Playwright MCP server (1.62) |
| npx playwright cli | Run the bundled playwright-cli for agents (1.62) |
A Playwright framework setup guide walks through the folder structure the scaffold does not create, such as fixtures and page objects. The next step after installing is the part most tests get wrong: finding elements.
Playwright locators cheatsheet: getByRole first, CSS last
Locators describe how to find an element and do nothing until an action or assertion uses them. That late binding is what makes auto-waiting work, and it is the reason the docs recommend locators over the older page.$() handles.
The official locators guide lists the built-in locators in priority order, and it is the one table in a Playwright cheat sheet worth memorising. Role first, because it reflects what a user or screen reader perceives, and raw CSS or XPath last, because they break on every refactor.
| Priority | Locator | Example | Use when |
|---|---|---|---|
| 1 | getByRole | page.getByRole('button', { name: 'Sign in' }) | Anything with an ARIA role: buttons, links, headings, checkboxes, dialogs |
| 2 | getByLabel | page.getByLabel('Password') | Form controls with a label, aria-label, or aria-labelledby |
| 3 | getByPlaceholder | page.getByPlaceholder('name@example.com') | Inputs that only have placeholder text |
| 4 | getByText | page.getByText('Welcome back', { exact: true }) | Non-interactive text such as messages and labels |
| 5 | getByAltText | page.getByAltText('Playwright logo') | Images and areas with alt text |
| 6 | getByTitle | page.getByTitle('Issues count') | Elements with a title attribute |
| 7 | getByTestId | page.getByTestId('order-total') | Stable hooks you control; attribute is data-testid by default |
| 8 | locator (CSS or XPath) | page.locator('css=.price'), page.locator('xpath=//td[2]') | Last resort for markup you cannot change |
getByRole accepts name as a string or regex plus exact, checked, disabled, expanded, pressed, selected, level for headings, includeHidden, and since 1.60 description for the accessible description. To change the test id attribute, set testIdAttribute: 'data-qa' under use in the config.
Filtering, chaining, and scoping
Every getBy method also exists on a locator, so you can narrow step by step. Playwright 1.63 and 1.64 added 2 methods that change how the chain reads.
| Method | Example | What it does |
|---|---|---|
| filter({ hasText }) | page.getByRole('row').filter({ hasText: 'Pending' }) | Keep matches containing text (case-insensitive substring or regex) |
| filter({ has }) | rows.filter({ has: page.getByRole('button', { name: 'Retry' }) }) | Keep matches that contain another locator |
| filter({ hasNot, hasNotText }) | rows.filter({ hasNotText: 'Archived' }) | Drop matches that contain text or a locator |
| filter({ visible: true }) | page.getByRole('button').filter({ visible: true }) | Keep only visible matches (1.51) |
| visible() | page.getByRole('button', { name: 'Menu' }).visible() | Shorthand for the visible filter; replaces :visible (1.63) |
| within(parent) | saveButton.within(page.getByRole('dialog')) | Scope a reusable locator inside each parent match (1.64) |
| and(other) | page.getByRole('button').and(page.getByTitle('Subscribe')) | Match both conditions |
| or(other) | page.getByText('Welcome').or(page.getByText('Sign in')) | Match either; add .first() if both can appear |
| first(), last(), nth(i) | page.getByRole('listitem').nth(2) | Pick by position; prefer a better locator when you can |
| frameLocator(sel) | page.frameLocator('#payment').getByLabel('Card number') | Reach into an iframe; with no selector it searches every frame (1.63) |
| contentFrame() | page.locator('iframe[name="editor"]').contentFrame() | Turn an iframe locator into a frame locator |
| describe(text) | page.getByTestId('btn-sub').describe('Subscribe button') | Name a locator for traces and reports (1.53) |
| count(), all() | for (const li of await items.all()) await li.click() | Work with lists; all() snapshots the list once |
The 2 newest methods solve old problems. within() reads in the order you would say it, and nth() resolves per parent, so cell.nth(2).within(row) is the third cell of every row instead of the third cell on the page. visible() chains onto semantic locators, which the :visible pseudo-class never could.
import { test, expect } from '@playwright/test';
test('only the visible retry button in the pending row is clicked', async ({ page }) => {
await page.goto('/orders');
const pendingRow = page.getByRole('row').filter({ hasText: 'Pending' });
const retry = page.getByRole('button', { name: 'Retry' });
// within() scopes the reusable button locator; visible() skips the hidden mobile clone.
await retry.within(pendingRow).visible().click();
await expect(pendingRow.getByText('Queued')).toBeVisible();
});
Note: Locators are strict. An action on a locator that matches 2 or more elements throws a strict mode violation instead of picking the first one. Count-based methods like count() and toHaveCount() are the exception. Treat the error as a prompt to tighten the locator, not as a reason to add .first().
For the reasoning behind that order, the Playwright locators guide goes deeper. To try a locator against real markup before it goes into a test, paste the HTML into the Playwright Locator Playground. Pages built on web components need 1 more rule: Playwright pierces open shadow roots automatically, and the shadow DOM in Playwright guide covers the closed ones.

Playwright actions cheatsheet: clicks, forms, keyboard, files, and drag
Every action on a locator auto-waits. Before a click, Playwright checks that the element is attached, visible, stable, enabled, and receives pointer events at the click point, then retries those checks until the action timeout. You do not write any of that.
| Action | Code | Notes |
|---|---|---|
| Click | await locator.click() | Options: button: 'right', clickCount: 2, modifiers: ['ControlOrMeta'], position: { x, y }, force: true |
| Double click | await locator.dblclick() | Same options as click |
| Hover | await locator.hover() | Triggers menus and tooltips |
| Fill | await locator.fill('qa@example.com') | Clears then sets the value; fires input and change |
| Clear | await locator.clear() | Empties an input or textarea |
| Type key by key | await locator.pressSequentially('hello', { delay: 50 }) | Only when the app listens to keydown; replaces type() |
| Press a key | await locator.press('Enter') | Combos: 'Control+ArrowRight', 'Shift+A', 'ControlOrMeta+S' |
| Check or uncheck | await locator.check(), await locator.setChecked(false) | Checkboxes and radios; asserts the final state |
| Select option | await locator.selectOption('blue') | By value or label; { label: 'Blue' }; arrays for multi-select |
| Upload a file | await locator.setInputFiles('fixtures/report.pdf') | Arrays for multiple; { name, mimeType, buffer } for in-memory; [] to clear |
| Drag and drop | await source.dragTo(target) | Manual: hover, page.mouse.down(), page.mouse.move(), page.mouse.up() |
| Drop data | await dropzone.drop({ files: ['fixtures/a.png'] }) | Simulates a drop without a source element (1.60) |
| Focus and blur | await locator.focus(), await locator.blur() | Useful for validation on blur |
| Scroll | await locator.scrollIntoViewIfNeeded() | Or page.mouse.wheel(0, 500) for infinite lists |
| Dispatch an event | await locator.dispatchEvent('click') | Skips actionability checks; last resort |
| Screenshot | await locator.screenshot({ path: 'card.png' }) | page.screenshot({ fullPage: true, mask: [ads] }) for the whole page |
Three interactions need an event listener set up before the action, because the event fires during the click. Start waiting first, click second, await the promise third.
import { test, expect } from '@playwright/test';
test('download, popup, and dialog in one flow', async ({ page }) => {
await page.goto('/reports');
// Downloads: register the wait before the click that triggers it.
const downloadPromise = page.waitForEvent('download');
await page.getByRole('link', { name: 'Export CSV' }).click();
const download = await downloadPromise;
await download.saveAs(`downloads/${download.suggestedFilename()}`);
// Popups: the new page arrives as an event on the opener.
const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'Open docs' }).click();
const popup = await popupPromise;
await expect(popup).toHaveTitle(/Docs/);
// Dialogs are auto-dismissed unless you handle them.
page.once('dialog', dialog => dialog.accept());
await page.getByRole('button', { name: 'Delete report' }).click();
await expect(page.getByText('Report deleted')).toBeVisible();
});
Tip: Reach for force: true only when an overlay intercepts the click by design, such as a transparent drag handle. Used anywhere else, it hides the exact bug a user would hit, and it is one of the most common Playwright mistakes in suites that migrated from Selenium.
Actions change the page. Assertions check that the change happened, and the right kind of assertion keeps waiting until it does.
Playwright assertions cheatsheet: web-first expect matchers
Playwright's expect has 2 kinds of matchers, and the official assertions reference lists every one. Web-first matchers take a locator, page, or response and retry until they pass or the expect timeout of 5 seconds runs out. Generic matchers take a plain value and check it once.
The practical rule: if the thing you are checking lives in the browser, pass the locator and await the assertion. await expect(locator).toBeVisible() retries. expect(await locator.isVisible()).toBe(true) checks a stale boolean and fails on the first slow render.
| Group | Matchers |
|---|---|
| Element state | toBeVisible, toBeHidden, toBeAttached, toBeEnabled, toBeDisabled, toBeEditable, toBeEmpty, toBeFocused, toBeChecked, toBeInViewport |
| Text and value | toHaveText, toContainText, toHaveValue, toHaveValues, toHaveCount |
| Attributes and styling | toHaveAttribute, toHaveClass, toContainClass, toHaveId, toHaveCSS, toHaveJSProperty |
| Accessibility | toHaveRole, toHaveAccessibleName, toHaveAccessibleDescription, toMatchAriaSnapshot |
| Page | toHaveURL, toHaveTitle, toHaveScreenshot, toMatchAriaSnapshot |
| API response | toBeOK |
| Generic (no retry) | toBe, toEqual, toStrictEqual, toContain, toContainEqual, toMatch, toMatchObject, toHaveLength, toHaveProperty, toBeTruthy, toBeNull, toBeGreaterThan, toThrow |
toHaveText matches the whole normalised text, and toContainText matches a substring. Both accept a regex and an array for lists. toHaveClass matches the full class string or a regex, while toContainClass checks that specific class names are present, which is usually what you mean.
import { test, expect } from '@playwright/test';
test('assertion patterns worth memorising', async ({ page }) => {
await page.goto('/cart');
await expect(page).toHaveURL(/\/cart$/);
await expect(page.getByRole('heading', { level: 1 })).toHaveText('Your cart');
await expect(page.getByRole('listitem')).toHaveCount(3);
await expect(page.getByTestId('total')).toContainText('$');
await expect(page.getByRole('button', { name: 'Checkout' })).toBeEnabled();
await expect(page.getByRole('alert')).not.toBeVisible();
// Custom message appears in the report next to the failure.
await expect(page.getByTestId('promo'), 'promo banner should render').toBeVisible();
// Soft assertions record the failure and keep going.
await expect.soft(page.getByTestId('eta')).toHaveText('2 days');
// Poll any async value until the matcher passes.
await expect.poll(async () => (await page.request.get('/api/cart')).status()).toBe(200);
// Retry a whole block of code, with an explicit timeout since toPass defaults to 0.
await expect(async () => {
const res = await page.request.get('/api/stock');
expect((await res.json()).count).toBeGreaterThan(0);
}).toPass({ timeout: 15_000 });
});
expect.configure({ timeout: 10_000 }) returns a pre-configured instance, and expect.configure({ soft: true }) makes every assertion soft in a block. expect.extend() adds custom matchers, which the Playwright assertions guide covers in depth.
Visual and accessibility snapshots use the same retrying model. toHaveScreenshot() compares against a baseline image, and toMatchAriaSnapshot() compares against a YAML view of the accessibility tree.
await expect(page.getByRole('navigation')).toMatchAriaSnapshot(`
- navigation:
- link "Docs"
- link "Pricing"
- link "Blog"
`);
await expect(page).toHaveScreenshot('home.png', { maxDiffPixelRatio: 0.01, fullPage: true });
The config section below shows how to store unnamed screenshots as WebP, a 1.64 option that shrinks baseline folders. Teams doing Playwright visual testing at scale should also read the Playwright timeout guide, because the expect timeout and the test timeout interact in ways that surprise people.
Playwright test structure cheatsheet: hooks, fixtures, tags, and locks
A spec file is a list of tests with optional groups, hooks, and details. The details object is where tags, annotations, and locks live, and it works on both test() and test.describe().
import { test, expect } from '@playwright/test';
test.describe('account settings', { tag: '@settings' }, () => {
test.describe.configure({ mode: 'serial', retries: 1, timeout: 60_000 });
test.beforeEach('open settings', async ({ page }) => {
await page.goto('/settings');
});
test('update notification settings', {
tag: ['@smoke', '@fast'],
annotation: { type: 'issue', description: 'https://github.com/org/app/issues/42' },
lock: 'user-settings', // no other test with this lock runs at the same time (1.63)
}, async ({ page }) => {
await test.step('enable alerts', async () => {
await page.getByLabel('Email alerts').check();
}, { box: true });
await test.step('save', async () => {
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByText('Saved')).toBeVisible();
}, { subtitle: 'alerts on', params: { channel: 'email' } }); // 1.63
test.info().annotations.push({ type: 'browser', description: test.info().project.name });
});
test.afterEach(async ({ page }, testInfo) => {
if (testInfo.status !== testInfo.expectedStatus) {
await testInfo.attach('final-state', { body: await page.screenshot(), contentType: 'image/png' });
}
});
});
Tags are filterable from the command line with --grep @smoke, and annotations show up in the HTML report. The lock name is a plain string, so there is nothing to configure. Playwright 1.64 extended locks to whole groups through test.describe.configure({ lock: 'billing' }).
| Control | Syntax | Effect |
|---|---|---|
| Skip | test.skip(condition, 'reason') inside the body, or test.skip('title', fn) | Not run; reason appears in the report |
| Fixme | test.fixme(({ browserName }) => browserName === 'webkit', 'reason') | Marked as needing a fix; not run |
| Expected failure | test.fail(condition, 'reason') | Runs; Playwright errors if it passes |
| Slow | test.slow() | Triples the test timeout |
| Focus | test.only('title', fn) | Only focused tests run; --forbid-only blocks it on CI |
| Timeout | test.setTimeout(120_000) | Overrides the timeout for this test or hook |
| Abort | test.abort('message') | Fails and stops immediately, even from a fixture or route handler (1.60) |
| Skip a step | test.step.skip('title', fn) | Step recorded as skipped (1.50) |
| Group mode | test.describe.configure({ mode: 'parallel' }) | 'serial' stops the group on first failure; 'parallel' runs tests across workers |
| Per-file options | test.use({ locale: 'fr-FR', storageState: 'admin.json' }) | Override any use option for a file or group |
Fixtures replace the beforeEach plus global variable pattern. A fixture sets something up, hands it to the test with use(), and tears it down afterwards. Worker-scoped fixtures run once per worker process, which is where expensive setup belongs.
import { test as base, expect } from '@playwright/test';
import { CartPage } from './pages/cart.page';
type Options = { currency: string };
type Fixtures = { cartPage: CartPage };
type WorkerFixtures = { apiToken: string };
export const test = base.extend<Options & Fixtures, WorkerFixtures>({
currency: ['USD', { option: true }], // overridable from config or test.use()
cartPage: async ({ page, currency }, use) => {
const cartPage = new CartPage(page, currency);
await cartPage.goto();
await use(cartPage);
await cartPage.clear(); // teardown runs after the test
},
apiToken: [async ({}, use) => {
const token = process.env.API_TOKEN ?? 'local-token';
await use(token);
}, { scope: 'worker' }],
});
export { expect };
Tests then import test from this file instead of from @playwright/test. The Playwright fixtures guide covers auto fixtures and option overrides, and the Playwright page object model guide shows the class behind CartPage. For tagging strategy, see Playwright annotations and grouping Playwright tests.

Playwright config cheatsheet: the options that decide how tests behave in CI
The config is where retries, parallelism, artifacts, and browsers are decided, which makes it the most-copied part of any Playwright config cheat sheet. The file below is a CI-grade starting point with every line that matters commented.
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true, // tests inside a file run across workers too
forbidOnly: !!process.env.CI, // fail CI if a test.only slipped through
retries: process.env.CI ? 2 : 0,
retryStrategy: 'isolated', // rerun failures at the end, one at a time (1.62)
workers: process.env.CI ? '50%' : undefined,
failOnFlakyTests: !!process.env.CI, // a pass-on-retry still fails the run
timeout: 30_000, // per test; default
expect: {
timeout: 5_000, // per assertion; default
toHaveScreenshot: { maxDiffPixelRatio: 0.01, type: 'webp' }, // WebP baselines (1.64)
},
reporter: process.env.CI
? [['blob'], ['github']] // blob for sharding, github for PR annotations
: [['html', { open: 'never' }], ['list']],
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
trace: 'on-first-retry', // cheapest mode that still explains a failure
screenshot: 'only-on-failure',
video: 'retain-on-failure',
testIdAttribute: 'data-qa',
actionTimeout: 10_000, // default is 0, meaning no limit
navigationTimeout: 15_000,
locale: 'en-US',
timezoneId: 'UTC',
},
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{ name: 'chromium', use: { ...devices['Desktop Chrome'] }, dependencies: ['setup'] },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] }, dependencies: ['setup'], default: false },
{ name: 'webkit', use: { ...devices['Desktop Safari'] }, dependencies: ['setup'], default: false },
{ name: 'mobile', use: { ...devices['iPhone 15'] }, dependencies: ['setup'], default: false },
],
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
});
default: false is new in 1.64. A project with that flag stays in the config and still runs on CI with --project="*", but a plain npx playwright test on a laptop skips it. The setup project runs anyway because the browsers list it as a dependency.
Timeouts and recording modes at a glance
Five timeouts apply to every test, and they nest. Knowing the defaults explains most "Timeout 30000ms exceeded" messages.
| Timeout | Default | Where to change it |
|---|---|---|
| Test | 30 seconds | timeout in config, test.setTimeout(), test.slow() |
| Expect | 5 seconds | expect.timeout in config, { timeout } on a matcher |
| Action | 0 (none) | use.actionTimeout, { timeout } on an action |
| Navigation | 0 (none) | use.navigationTimeout, { timeout } on goto |
| Global | 0 (none) | globalTimeout in config, --global-timeout |
| Web server | 60 seconds | webServer.timeout |
Trace, screenshot, and video share the same set of modes. The mode decides how much CI storage you pay for and how much evidence you get back.
| Mode | Records | Keeps | Best for |
|---|---|---|---|
| off | Nothing | Nothing | Local runs where you use UI mode instead |
| on | Every test | Everything | Short suites, demos |
| retain-on-failure | Every test | Failures only | Suites without retries |
| on-first-retry | First retry only | That retry | CI with retries; the usual default |
| on-all-retries | Every retry | All retries | Flake investigations |
| retain-on-first-failure | First attempt | First failure | Seeing the original failure, not the retry |
| retain-on-failure-and-retries | Every attempt | Failures and retries | Comparing a failed attempt with its retry |
Tip: The Playwright Config Generator produces a config like the one above from a few checkboxes, and the Trace Configurator shows the storage cost of each trace mode for your run size.
Workers, shards, and browser matrices each have a full guide: Playwright parallel execution, Playwright sharding, and optimize Playwright workers. The same config runs in GitHub Actions and in the official image for Playwright in Docker. For device projects, the Playwright mobile testing guide lists which emulation options each engine honours, and cross-browser testing with Playwright covers the differences between Chromium, Firefox, and WebKit.
Navigation, waiting, and network mocking cheatsheet
Most waiting in Playwright is implicit. Actions wait for actionability and assertions retry, so the explicit waits below are for the gaps between them: a navigation, a network response, or a state the UI does not expose.
| Need | Code | Notes |
|---|---|---|
| Navigate | await page.goto('/dashboard', { waitUntil: 'domcontentloaded' }) | Relative to baseURL; waitUntil: 'commit', 'domcontentloaded', 'load', 'networkidle' |
| History | await page.goBack(), await page.goForward(), await page.reload() | Same waitUntil options |
| Wait for a URL | await page.waitForURL('**/orders/*') | Glob or regex; replaces waitForNavigation |
| Wait for load state | await popup.waitForLoadState('domcontentloaded') | 'networkidle' is discouraged for tests |
| Wait for a response | const res = await page.waitForResponse(r => r.url().includes('/api/cart') && r.ok()) | Start before the action that triggers it |
| Wait for a request | await page.waitForRequest('**/api/track') | String, regex, or predicate |
| Wait for an element state | await locator.waitFor({ state: 'hidden' }) | 'attached', 'detached', 'visible', 'hidden' |
| Wait for a condition | await page.waitForFunction(() => window.appReady === true) | Runs in the page; polls on animation frames |
| Control time | await page.clock.install({ time: new Date('2026-10-20T09:00:00') }) | Then page.clock.fastForward('01:00') or setFixedTime() |
| Go offline | await context.setOffline(true) | Or test.use({ offline: true }) |
page.waitForTimeout() is missing from that table on purpose. A fixed sleep is either too short, which makes the test flaky, or too long, which makes the suite slow, and it is the first thing to remove when a test turns up in a Playwright flaky tests report.
Route, mock, and inspect network traffic
page.route() intercepts requests matching a glob or regex before they leave the browser. From the handler you can fulfil, abort, or continue, and since 1.62 the handler also receives an abort signal when the test ends.
import { test, expect } from '@playwright/test';
test('mock, modify, block, and observe', async ({ page, context }) => {
// Fulfil with JSON; status defaults to 200 and content-type is set for you.
await page.route('**/api/v1/products', route => route.fulfill({
json: [{ id: 1, name: 'Playwright mug', price: 18 }],
}));
// Fetch the real response, then patch it. times: 1 removes the route after one use.
await page.route('**/api/v1/profile', async route => {
const response = await route.fetch();
const json = await response.json();
json.plan = 'enterprise';
await route.fulfill({ response, json });
}, { times: 1 });
// Block analytics and images for speed.
await context.route(/\.(png|jpg|jpeg|webp)$/, route => route.abort());
await page.route('**/analytics/**', route => route.abort());
// Continue with a changed header.
await page.route('**/api/**', async route => {
const headers = { ...route.request().headers(), 'x-test-run': 'cheatsheet' };
await route.continue({ headers });
});
// Observe traffic without changing it.
page.on('response', res => { if (!res.ok()) console.log('<<', res.status(), res.url()); });
await page.goto('/shop');
await expect(page.getByText('Playwright mug')).toBeVisible();
const failed = await page.waitForResponse('**/api/v1/checkout').catch(() => null);
expect(failed).toBeNull();
});
Use route.fulfill({ status: 500, body: 'oops' }) to test error states and route.fulfill({ path: 'fixtures/avatar.png' }) to serve a file. page.unrouteAll({ behavior: 'ignoreErrors' }) removes every handler at the end of a test that registered many.
For whole-page replay, record a HAR once and serve it back. For WebSockets, routeWebSocket mocks the socket or sits between the page and the real server.
// Record with update: true once, then commit the HAR and flip it to false.
await page.routeFromHAR('./hars/catalog.har', { url: '**/api/**', update: false, notFound: 'fallback' });
await page.routeWebSocket('wss://example.com/ws', ws => {
ws.onMessage(message => {
if (message === 'ping') ws.send('pong');
});
});
The Playwright network mocking guide covers HAR update strategies and when a mock hides a real bug, and the official mock APIs guide has the full option list. The next section handles the request type most suites cannot mock: the login.
Authentication, storage state, and API testing cheatsheet
Playwright's recommended auth pattern signs in once, saves cookies and local storage to a file, and starts every test from that file. A setup project runs first, and the browser projects depend on it.
import { test as setup, expect } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.E2E_USER!);
await page.getByLabel('Password').fill(process.env.E2E_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('link', { name: 'Account' })).toBeVisible();
await page.context().storageState({ path: authFile }); // cookies, localStorage, IndexedDB
});
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],
Add playwright/.auth to .gitignore. For a file that needs a different user, or none, override the state at the top of the spec.
test.use({ storageState: 'playwright/.auth/admin.json' });
// tests/public.spec.ts
test.use({ storageState: { cookies: [], origins: [] } }); // signed out
Playwright 1.61 added direct web storage access, which removes most page.evaluate() calls from auth helpers. page.localStorage and page.sessionStorage expose getItem, setItem, removeItem, clear, and items().
await page.goto('/');
await page.localStorage.setItem('feature-flags', JSON.stringify({ newCheckout: true }));
await page.reload();
expect(await page.sessionStorage.getItem('visited')).toBe('true');
Per-worker accounts, session storage restore, and passkey logins are covered in the Playwright authentication guide, which follows the structure of the official authentication docs. HTTP basic auth is 1 line in config, httpCredentials: { username, password }, and 1.63 accepts an array for sites with more than 1 realm.
API testing with the request fixture
The request fixture is an APIRequestContext that shares no cookies with the browser. page.request is the one that does. Both support get, post, put, patch, delete, head, and fetch with data, form, multipart, headers, and params options.
import { test, expect } from '@playwright/test';
type Order = { id: number; status: string };
test('create and read an order through the API', async ({ request }) => {
const created = await request.post('/api/orders', {
data: { sku: 'MUG-01', qty: 2 },
headers: { Authorization: `Bearer ${process.env.API_TOKEN}` },
});
await expect(created).toBeOK(); // 2xx or 3xx
const order = await created.json() as Order;
const read = await request.get<Order>(`/api/orders/${order.id}`); // typed body (1.63)
expect(read.status()).toBe(200);
expect((await read.json()).status).toBe('pending');
expect((await read.timing()).responseEnd).toBeLessThan(1_000); // 1.62
await request.addCookies([{ name: 'ab', value: 'B', url: process.env.BASE_URL! }]); // 1.64
});
Set baseURL and extraHTTPHeaders under use once instead of repeating them. To mix API setup with a browser test, call request.storageState({ path }) after an API login and pass that file to the browser context. The Playwright API testing guide has the standalone playwright.request.newContext() pattern for scripts outside the runner.
Debugging and reporting cheatsheet: UI mode, trace viewer, and reporters
When a test fails, the question is always the same: what did the page look like at that moment? Playwright answers it 3 ways, and each fits a different situation.
| Tool | How to start it | Best for |
|---|---|---|
| UI mode | npx playwright test --ui | Local development: watch mode, time travel, pick locator, network tab |
| Inspector | npx playwright test --debug, or await page.pause() in the test | Stepping through 1 test with the browser open |
| Trace viewer | npx playwright show-trace trace.zip, or drag the zip onto trace.playwright.dev | CI failures: DOM snapshots, console, network, source per action |
| Headed run | npx playwright test --headed --workers 1 | Watching the browser without stopping |
| Verbose API log | DEBUG=pw:api npx playwright test | Seeing every Playwright call and its timing |
| Console and errors in code | await page.consoleMessages({ filter: 'since-navigation' }), await page.pageErrors() | Asserting on browser logs (1.56) |
| Screencast | await page.screencast.start({ path: 'walkthrough.webm', fps: 30 }) | Recording part of a test as a video (1.59) |
The trace is the artifact worth configuring well, because it is the only one that works after the fact on a CI machine you cannot open. The Playwright trace viewer guide explains each panel, and Playwright UI mode covers the local workflow.
await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
await page.goto('/checkout');
await context.tracing.stop({ path: 'traces/checkout.zip' });
Reporters and artifacts
Playwright ships 10 reporters, and the --add-reporter flag from 1.63 lets CI append one without editing the config.
| Reporter | Output | Use it for |
|---|---|---|
| list | One line per test with status | Local default |
| line | Single updating line | Large suites locally |
| dot | One character per test | CI default |
| html | Interactive report with traces and attachments | Sharing a run; open: 'never' on CI |
| github | Workflow annotations on failing lines | GitHub Actions |
| json, junit | Machine-readable files | Dashboards, CI systems that read JUnit |
| blob | Raw results per shard | merge-reports after sharding |
| perfetto | Timeline with a lane per worker | Finding slow workers and long fixtures (1.63) |
| null | Nothing | Silencing a reporter in a sub-run |
| custom file | Whatever your Reporter class emits | Posting to Slack, a database, or an API |
npx playwright test --shard 2/4 --reporter blob
npx playwright merge-reports --reporter html ./all-blob-reports
The built-in Playwright HTML reporter is a per-run file, which is fine for 1 run and painful for 400. A Playwright custom reporter can push results anywhere, and the broader Playwright test reporting guide compares the options.
Flaky tests deserve their own corner of the Playwright cheatsheet: 4 commands. Run the suspect repeatedly, shuffle the order, retry in isolation, and make retries count as failures so they cannot hide.
npx playwright test -g "checkout" --repeat-each 20 # does it fail on its own?
npx playwright test --shuffle # does it depend on order? (1.64)
npx playwright test --retries 2 --fail-on-flaky-tests # pass-on-retry still fails the run
npx playwright test --last-failed --trace on # rerun yesterday's failures with full traces
Across many runs, the pattern matters more than any single trace. TestDino's test case history shows the same test across every branch and run, its error grouping collapses identical failures into 1 pattern, and the embedded trace viewer opens a CI trace without downloading the zip. The rerun only failed tests guide shows how that feeds back into --last-failed.

Playwright for AI agents: MCP, playwright-cli, and aria snapshots
Playwright has become the default browser layer for AI coding agents, and several of the APIs in this Playwright cheatsheet exist for that reason. An agent needs a text view of the page, a way to act on it, and a way to turn what it did into a deterministic test. The table below maps the tools to those 3 jobs.
| Tool | Command or API | What it gives an agent |
|---|---|---|
| Playwright MCP | npx playwright mcp, or npx @playwright/mcp@latest | Browser tools over the Model Context Protocol for Claude Code, Cursor, VS Code, and others |
| playwright-cli | npm i -g @playwright/cli@latest, then playwright-cli open, snapshot, click e3, fill e5 "text", screenshot, run-code | The same actions as shell commands, using far fewer tokens than MCP |
| Test agents | npx playwright init-agents --loop=claude | Planner, generator, and healer definitions that write specs/ and tests/ |
| Agent debugging | npx playwright test --debug=cli | Pauses a test so an agent can attach through playwright-cli (1.59) |
| Aria snapshot | await page.ariaSnapshot({ mode: 'ai' }) | Accessibility tree as text, with element refs like [ref=e2] |
| Ref locator | page.getByRef('e2') | Replays an agent's click as a locator (1.64) |
| JSON tree | await locator.ariaSnapshotJSON({ depth: 2 }) | The same tree as data you can walk in code (1.63) |
| WebMCP | await page.webmcp.tools(), await page.webmcp.callTool(name, input) | Lists and calls tools a page registers for agents; Chromium only (1.64) |
| Skill file | playwright-cli install --skills | Reference guides an agent reads before writing tests |
The snapshot plus ref pair is the bridge between an exploratory agent session and a committed test. An agent reports that it clicked e7; the test takes the same snapshot and clicks the same ref.
const snapshot = await page.ariaSnapshot({ mode: 'ai' });
console.log(snapshot);
// - button "Submit" [ref=e2]
await page.getByRef('e2').click();
For most teams the right order is: generate with an agent, then rewrite refs into role-based locators before merging, so the test survives a redesign. The Playwright MCP and playwright-cli guides set up each tool, the playwright-cli repository lists every command, and Playwright CLI vs MCP measures the token difference. The Playwright test agents guide covers the planner, generator, and healer loop from the official test agents docs, and AGENTS.md for Playwright shows what to tell an agent before it writes its first test.
Note: An MCP server runs with your credentials and can be driven by page content. Read the MCP server security checklist before pointing an agent at a signed-in session, and keep playwright/.auth files out of any directory an agent can read.
If you use Claude Code, Cursor, or Codex to write tests, the open-source TestDino Playwright skill encodes the locator priority, assertion rules, and config patterns from this page, so the agent follows them without being told each time.
Deprecated Playwright APIs and their 2026 replacements
Every row in this table is something a Playwright cheatsheet published before 2024 is likely to show. Some are deprecated, some are removed, and some still work but are documented as discouraged. All of them have a shorter, more reliable replacement today.
| Old API | Status | Use instead |
|---|---|---|
| page.click('#btn'), page.fill(sel), page.check(sel) | Discouraged since locators arrived | page.getByRole('button', { name }).click(), locator.fill() |
| page.$(), page.$$(), page.$eval(), ElementHandle | Discouraged | page.locator(), locator.evaluate(), locator.all() |
| page.type(), locator.type() | Deprecated | locator.fill(), or locator.pressSequentially() when key events matter |
| page.waitForSelector(sel, { state: 'visible' }) | Discouraged | await expect(locator).toBeVisible(), locator.waitFor() |
| page.waitForTimeout(3000) | Documented as never for production | Web-first assertions, waitForResponse, waitForURL |
| page.waitForNavigation() | Deprecated | page.waitForURL(), or an assertion on the new page |
| page.locator('button:visible') | Still works | locator.visible() (1.63), which chains onto getByRole |
| page.frame({ name }) then frame.click() | Discouraged | page.frameLocator(sel), locator.contentFrame() |
| page.setOfflineMode(true) | Never a Playwright API (it is Puppeteer) | context.setOffline(true), test.use({ offline: true }) |
| page.accessibility.snapshot() | Deprecated | locator.ariaSnapshot(), expect().toMatchAriaSnapshot() |
| test.describe.serial(), test.describe.parallel() | Deprecated | test.describe.configure({ mode: 'serial' }) |
| expect(await locator.isVisible()).toBe(true) | Works, does not retry | await expect(locator).toBeVisible() |
| locator.elementHandle() | Discouraged | Stay on the locator; use evaluate() for DOM access |
| _react= and _vue= selectors, :light suffix | Removed in 1.58 | getByRole, getByTestId; shadow DOM is pierced by default |
| devtools launch option | Removed in 1.58 | --headed with --debug, or UI mode |
| Locator.ariaRef() | Removed in 1.60 | page.getByRef() (1.64) |
| videosPath, videoSize context options | Removed in 1.60 | recordVideo: { dir, size, fps } |
| fontSize in screencast showActions | Deprecated in 1.64 | style: { title: 'font-size: 14px' } |
| @playwright/experimental-ct-react, -vue, -svelte | Svelte removed in 1.59; React and Vue frozen in 1.63 | The stories model with the mount fixture (1.62) |
| require('playwright') scripts for tests | Library, not the runner | import { test, expect } from '@playwright/test' |
| browser.newContext() in every test | Manual lifecycle | The page and context fixtures, which isolate per test |
| Node.js 12 to 20 | Unsupported | Node.js 22, 24, or 26 |
Three of these rows account for most of the flakiness in suites that migrated from another tool. Element handles go stale when a framework re-renders, fixed sleeps race the network, and isVisible() inside a plain expect checks once and gives up. Moving each one to its locator-based replacement is a mechanical change that the Selenium to Playwright migration and Cypress to Playwright migration guides walk through file by file.
The broader rules for keeping a suite current are in Playwright best practices. If your team writes Playwright outside TypeScript, the same API exists in the Python Playwright tutorial, Playwright with Java, and Playwright with .NET guides, with method names adjusted to each language's conventions.
Conclusion
A Playwright cheatsheet is only useful if it matches the version you have installed. This one tracks Playwright 1.64 and the test runner: npm init playwright@latest to start, role-based locators to find elements, auto-waiting actions to change them, web-first expect matchers to check them, and a config that sets retries, traces, and projects once for every CI run.
The newest methods are the ones to try first, because each removes a workaround. locator.within() and locator.visible() replace CSS tricks, --shuffle exposes order dependencies, retryStrategy: 'isolated' makes retries honest, and page.getByRef() turns an agent's session into a test.
Pick 1 file in your suite, run it against the deprecated API table in this Playwright cheat sheet, and replace what you find. Then open the Playwright 1.63 and Playwright 1.62 release guides for the features that did not fit on this page, such as component testing with the stories model, which has its own Playwright component testing guide.
FAQs

Pratik Patel
Co-founder