Skip to content

Menu

Playwright Cheat Sheet: Locators, Assertions, CLI and Config

Checked against Playwright Playwright 1.65 docs (v1.65.1 tag, 13 Nov 2026); examples run on Playwright 1.49.1 on 28 November 2026. Each section links to the official docs it was checked against.

This sheet is for people writing end-to-end tests with Playwright Test in JavaScript or TypeScript. It follows the playwright.dev docs for 1.65, the current release line. The locator and assertion rows were run against a local page with Playwright 1.49.1, the copy installed in our repo, and rows marked untested were checked in the docs only.

When to use what

Start every locator with getByRole and a name. It reads like what a user sees ("the Save button"), it survives class renames, and a failing role query often tells you the markup is missing a label. Reach for getByLabel on form fields and getByText for plain content. Keep getByTestId for things with no stable text, such as a cart badge, and drop to CSS or XPath through page.locator() only when nothing else fits; the docs call long CSS chains a bad practice because they break as soon as the DOM shifts. The Playwright selector builder helps when you are unsure which form to write.

For checks, use the async expect(locator) matchers such as toHaveText and toBeVisible. They retry until the page catches up, five seconds by default. A plain expect(await locator.textContent()) reads once and fails on any slow render, which is where most flaky tests come from. If you are still picking a runner, our test runner comparison covers where Playwright fits next to Vitest and Cypress, and the Playwright MCP server lets an AI agent drive a browser with the same engine.

The order below is the one the docs recommend. Actions on a locator that matches more than one element throw a strict mode error; first(), last() and nth() opt out of that check, but the docs warn they break when the page order changes.

page.getByRole('button', { name: 'Save' })

Find an element by its ARIA role and accessible name, the first choice for anything a user clicks

page.getByRole('heading', { name: 'Settings', level: 2 })

Match an h2 heading by its text, narrowing by heading level

page.getByText('Saved 3 items')

Find non-interactive content by its visible text; add { exact: true } for a whole, case-sensitive match

page.getByLabel('Email')

Find a form control through the text of its associated label

page.getByPlaceholder('Search docs')

Find an input by its placeholder when it has no visible label

page.getByAltText('Logo')

Find an image by its alt text

page.getByTitle('Issues count')

Find an element by its title attribute

From the docs, not run by us
page.getByTestId('cart')

Find an element by data-testid; change the attribute name with testIdAttribute in config

page.locator('#msg')

Fall back to a CSS selector when no user-facing locator fits; CSS and XPath are auto-detected

page.getByRole('listitem').filter({ hasText: 'Ban' })

Keep only list items containing the text, case-insensitive, string or regex

rows.filter({ hasNotText: 'Out of stock' })

Drop matches that contain the given text

From the docs, not run by us
rows.filter({ has: page.getByRole('button', { name: 'Buy' }) })

Keep elements that contain a descendant matching another locator

From the docs, not run by us
page.getByRole('button').and(page.getByTitle('Subscribe'))

Match elements that satisfy both locators at once

From the docs, not run by us
newBtn.or(dialog).first()

Match either locator; add .first() because both matching is a strict mode violation

From the docs, not run by us
page.getByRole('listitem').nth(1)

Pick the second match by zero-based index; fragile if the order changes

These retry until they pass or time out. The default is 5 seconds; change it with expect: { timeout } in config or per call.

await expect(page.getByText('Saved 3 items')).toBeVisible()

Wait until the element is visible, retrying while the page updates

await expect(locator).toHaveText(/Saved \d+ items/)

Assert the full text of the element, here with a regex

await expect(locator).toContainText('2 items')

Assert that the text includes a substring

await expect(page.getByRole('listitem')).toHaveCount(2)

Wait until exactly two elements match

await expect(page.getByLabel('Email')).toHaveValue('[email protected]')

Assert the current value of an input

await expect(page).toHaveURL(/\/dashboard/)

Wait for the page URL to match after a navigation

From the docs, not run by us
await expect.soft(locator).toHaveText('Apple')

Record a failure but keep running the rest of the test

await expect.poll(() => getStatus()).toBe('done')

Retry a plain function until the matcher passes; intervals default to 100, 250, 500 and 1000 ms

From the docs, not run by us
await expect(locator).not.toBeVisible()

Negate any matcher with .not

From the docs, not run by us

Before an action, Playwright waits for the checks in the table on that page. click needs the element to be visible, stable, enabled, not inert and to receive the pointer events; fill needs visible, enabled, editable and not inert.

await page.getByRole('button', { name: 'Save' }).click()

Click after waiting for the button to be visible, stable, enabled and hit-testable

await page.getByLabel('Email').fill('[email protected]')

Clear the field and type the value, after waiting for it to be editable

await page.getByRole('checkbox').check()

Tick a checkbox, with the same waits as click

From the docs, not run by us
await locator.click({ force: true })

Skip non-essential actionability checks, for example the receives-events check

From the docs, not run by us
await page.goto('/')

Open a page relative to use.baseURL from the config

From the docs, not run by us
npx playwright test

Run every test headless with the config in the current folder

npx playwright test tests/login.spec.ts:42

Run only the test at that line of the file

From the docs, not run by us
npx playwright test -g "checkout"

Run tests whose titles match a regular expression

From the docs, not run by us
npx playwright test --ui

Open UI mode to pick, watch and time-travel through tests

From the docs, not run by us
npx playwright test --debug

Run with the Playwright Inspector; also sets headed, one worker and no timeout

From the docs, not run by us
npx playwright test --headed --project=chromium

Show the browser and limit the run to one project

From the docs, not run by us
npx playwright test --last-failed

Re-run only the tests that failed in the previous run

From the docs, not run by us
npx playwright test --repeat-each=10 --workers=1

Run each test ten times in one worker to shake out flakiness

From the docs, not run by us
npx playwright test --trace=retain-on-failure

Record a trace for every test and keep only the failing ones

From the docs, not run by us
npx playwright codegen -o tests/new.spec.ts http://localhost:3000

Record clicks in a browser and write them as test code

From the docs, not run by us
npx playwright show-report

Serve the last HTML report, on port 9323 by default

From the docs, not run by us
npx playwright show-trace trace.zip

Open a saved trace in the trace viewer

From the docs, not run by us
npx playwright install --with-deps chromium

Download Chromium plus the OS packages it needs, usually on CI

From the docs, not run by us
testDir: 'tests'

Folder that holds the test files, relative to the config

From the docs, not run by us
fullyParallel: true

Run tests inside each file in parallel, not only files

From the docs, not run by us
forbidOnly: !!process.env.CI

Fail the CI run if someone left a test.only in the code

From the docs, not run by us
retries: process.env.CI ? 2 : 0

Retry failures twice on CI and never locally

From the docs, not run by us
use: { baseURL: 'http://localhost:3000', trace: 'on-first-retry' }

Set the base for page.goto('/') and keep a trace when a test is retried

projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }]

Define a browser or device configuration to run the suite against

From the docs, not run by us
webServer: { command: 'npm run start', url: 'http://localhost:3000', reuseExistingServer: !process.env.CI }

Start your app before the tests and reuse an already running one locally

From the docs, not run by us
timeout: 30000, expect: { timeout: 5000 }

Per-test timeout and the retry window for each expect

From the docs, not run by us

Worked example: Catch a strict mode violation and fix it with a filter

A test clicked a list item and failed straight away. Running it shows why:

// demo.spec.mjs
import { test, expect } from 'playwright/test';

test('strict', async ({ page }) => {
  await page.setContent('<ul><li>Apple</li><li>Banana</li></ul>');
  await page.getByRole('listitem').click({ timeout: 1000 });
});
$ npx playwright test
  ✘  demo.spec.mjs:3:1 › strict (71ms)
    Error: locator.click: Error: strict mode violation: getByRole('listitem') resolved to 2 elements:
        1) <li>Apple</li> aka getByText('Apple')
        2) <li>Banana</li> aka getByText('Banana')

The locator matched two items, and Playwright refuses to guess which one you meant. The error even suggests a narrower locator for each match. Fix it by saying which item you want in words, not by position:

await page.getByRole('listitem').filter({ hasText: 'Banana' }).click();
await expect(page.getByRole('listitem')).toHaveCount(2);

The filtered version passed in our run. Reaching for .first() would also silence the error, but the test would quietly start clicking a different item the day someone sorts the list. Counting with toHaveCount is fine on a multi-match locator, because only actions are strict.

Common mistakes

  • Reading text with await locator.textContent() and comparing it with a plain expect.

    Use await expect(locator).toHaveText(...) so the check retries while the page renders.

  • Adding await page.waitForTimeout(2000) to make a flaky step pass.

    Wait on the condition itself with a web-first assertion; actions already wait for actionability.

  • Silencing a strict mode error with .first() or .nth(0).

    Narrow the locator by role name, label or filter({ hasText }) so it targets one element on purpose.

  • Writing long CSS chains such as #main > div:nth-child(2) .btn copied from DevTools.

    Use getByRole with a name, or add a data-testid and use getByTestId.

  • Forgetting await before expect(locator) matchers, so the test finishes before the assertion runs.

    Always await locator assertions.

  • Turning trace on for every run and filling CI storage.

    Use trace: 'on-first-retry' or --trace=retain-on-failure so you keep traces only when something failed.