Playwright cheat sheet: locators, actions and assertions

6 min read · TypeScript · 23 linked exercises

The Playwright API you use every day, on one page. All examples are TypeScript for the Playwright test runner. Each section ends with exercises where you can try the calls on a real page.

New to Playwright? Start with the four-week practice plan and come back here when you need to look something up.

Commands

npm init playwright@latest               # create a project

npx playwright test                      # run every test, headless
npx playwright test login.spec.ts        # one file
npx playwright test -g "adds to cart"    # tests whose title matches
npx playwright test --project=chromium   # one browser project
npx playwright test --headed             # show the browser
npx playwright test --ui                 # UI mode: watch, step, pick locators
npx playwright test --debug              # step through with the Inspector
npx playwright test --trace on           # record a trace for every test
npx playwright test --repeat-each=20     # run each test 20 times
npx playwright test --workers=4          # number of parallel workers
npx playwright test --last-failed        # only the tests that failed last time

npx playwright show-report               # open the HTML report
npx playwright show-trace trace.zip      # open a trace file

# record your actions as test code
npx playwright codegen https://playwright-playground.com

Locators

Prefer the locators at the top of the table. The locators guide explains the order.

LocatorWhat it does
page.getByRole('button', { name: 'Save' })By role and accessible name
page.getByLabel('Email')A form field by its label
page.getByPlaceholder('Search')An input by its placeholder
page.getByText('Welcome back')Any element by its text
page.getByAltText('Logo')An image by its alt text
page.getByTitle('Close')By the title attribute
page.getByTestId('cart-total')By data-testid
page.locator('.card')By CSS, the last resort
{ name: 'Save', exact: true }Whole name, case-sensitive. The default is a substring
rows.filter({ hasText: 'Ada' })Keep the matches that contain a text
cards.filter({ has: page.getByRole('img') })Keep the matches that contain another locator
row.getByRole('button', { name: 'Edit' })Search inside another locator
items.first(), items.last(), items.nth(2)By position, counted from 0
saveButton.or(retryButton)Whichever of the two is there
Practise it
  • Locator ChallengesIntermediateFind one exact element in each section, without CSS or test ids.

Actions

Actions wait until the element is ready. A click, for example, waits until it's visible, stable, enabled and not covered by something else.

ActionWhat it does
page.goto('/cart')Open a path under baseURL
locator.click()Click. Also dblclick()
locator.click({ button: 'right' })Right-click
locator.click({ modifiers: ['Shift'] })Click with a key held
locator.fill('Ada')Replace the value of an input
locator.clear()Empty an input
locator.pressSequentially('Ada')Type key by key, for inputs that react to each key
locator.press('Enter')Press a key on the element
page.keyboard.press('ControlOrMeta+A')A shortcut that works on every system
locator.check(), locator.uncheck()Checkboxes and radio buttons
locator.setChecked(true)Check or uncheck from a variable
locator.selectOption('Blue')Choose in a <select>, by value or label
locator.hover()Move the mouse over the element
source.dragTo(target)Drag and drop
page.mouse.move(x, y)Low-level mouse: also down(), up(), wheel()
locator.focus(), locator.blur()Move focus in or out
page.reload(), page.goBack()Browser navigation
Practise it
  • ButtonsBeginnerClick, double-click and right-click.
  • InputsBeginnerfill(), clear() and pressSequentially().
  • CheckboxesBeginnercheck(), uncheck() and setChecked().
  • DropdownBeginnerselectOption() and a custom dropdown.
  • HoverBeginnerMenus and tooltips that need hover().
  • Keyboard ActionsBeginnerKeys, shortcuts and Tab order.
  • Drag & DropIntermediatedragTo(), manual mouse moves and keyboard dragging.
  • Mouse ActionsIntermediateModifier clicks, positions and the wheel.

Assertions

Assertions on a locator or the page retry until they pass or time out, after 5 seconds by default. Always await them.

await expect(locator)…What it does
.toBeVisible(), .toBeHidden()Shown, or hidden or absent
.toBeEnabled(), .toBeDisabled()Whether it can be used
.toBeChecked()A checkbox or radio button is checked
.toBeFocused()Has keyboard focus
.toHaveText('Saved')The whole text
.toContainText('Sav')A part of the text
.toHaveText(/saved/i)Text that matches a regular expression
.toHaveText(['Ada', 'Grace'])The text of every match, in order
.toHaveValue('ada@example.com')The value of an input
.toHaveCount(3)The number of matches
.toHaveAttribute('href', '/pricing')An attribute
.toHaveClass(/active/)The class attribute
.toHaveCSS('color', 'rgb(255, 0, 0)')A computed style
.toHaveAccessibleName('Close')The name a screen reader announces
.not.toBeVisible()The opposite of any assertion
expect(page).toHaveURL('/cart')The address. Also toHaveTitle()
expect.soft(locator)Record a failure and carry on
expect(value).toBe(3)A value you already have. Does not retry. Also toEqual(), toContain()
Practise it

Waiting

Actions and assertions already wait. Add your own wait only for something they can't see. The auto-waiting guide has the details.

WaitWhat it does
expect(locator).toBeVisible({ timeout: 10_000 })A longer timeout for one slow element
page.waitForResponse('**/api/users')A response. Start it before the action that triggers it
page.waitForURL('**/dashboard')A navigation
expect.poll(() => getCount()).toBe(3)Retry a function until its result matches
expect(async () => { … }).toPass()Retry a block of actions and assertions
locator.waitFor({ state: 'hidden' })A state, without asserting
page.clock.install(), page.clock.fastForward(30_000)Control time instead of waiting for it
page.waitForTimeout(1000)A fixed sleep. Avoid it: too long when fast, too short when slow
const responsePromise = page.waitForResponse('**/api/users');
await page.getByRole('button', { name: 'Load users' }).click();
const response = await responsePromise;
Practise it

Network

Set up a route before the action that sends the request. More in the network mocking guide.

CallWhat it does
page.route('**/api/users', (route) => route.fulfill({ json: [] }))Answer a request yourself
route.fulfill({ status: 500 })Simulate a server error
route.abort()Simulate a network failure
route.continue()Let the request through
route.fetch()Get the real response, to change it before fulfilling
page.waitForRequest('**/api/orders')A request the page sends. Read it with postDataJSON()
response.status(), await response.json()Read a response
request.get('/api/users')Call an API without a browser. Also post(), put(), patch(), delete()
request.post('/api/users', { data: { name: 'Ada' } })Send a JSON body
await expect(response).toBeOK()The status is between 200 and 299
Practise it

Frames, dialogs, tabs and files

CallWhat it does
page.getByTitle('Payment').contentFrame()Enter an iframe, then use locators inside it
page.once('dialog', (dialog) => dialog.accept())Answer an alert, confirm or prompt. Register it before the click
dialog.message(), dialog.dismiss()Read a dialog, or cancel it
page.waitForEvent('popup')A new tab or window opened by the page
context.newPage(), context.pages()Open a tab yourself, or list the open ones
locator.setInputFiles('report.pdf')Upload a file. An empty array clears it
locator.setInputFiles({ name, mimeType, buffer })Upload a file made in the test
page.waitForEvent('download')A download. Then suggestedFilename(), path(), saveAs()
context.storageState({ path })Save cookies and localStorage, to start signed in

Events follow one pattern: start waiting, act, then await.

const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'Open report' }).click();
const popup = await popupPromise;

await expect(popup.getByRole('heading', { name: 'Report' })).toBeVisible();

Guides: iframes, file upload and download, authentication.

Practise it

Test structure

import { expect, test } from '@playwright/test';

test.describe('Cart', () => {
  // Options for every test in this group
  test.use({ viewport: { width: 390, height: 844 } });

  test.beforeEach(async ({ page }) => {
    await page.goto('/shop');
  });

  test('adds a product', async ({ page }) => {
    await test.step('Add to cart', async () => {
      // …
    });
  });
});

// One test per row of data
for (const name of ['Ada', 'Grace']) {
  test(`greets ${name}`, async ({ page }) => {
    // …
  });
}
CallWhat it does
test.only(…)Run only this test. Never commit it
test.skip(…)Don't run this test
test.fixme(…)Don't run it, and mark it as needing a fix
test.slow()Triple the timeout of this test
test.describe.configure({ mode: 'serial' })Run a group in order, and stop it at the first failure
base.extend({ … })Add your own fixtures
testInfo.attach('log', { body })Add a file or text to the report
await page.pause()Stop here and open the Inspector

The Page Objects and fixtures guide shows how to organise a larger suite.

Practise it

Config essentials

// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  retries: process.env.CI ? 2 : 0,
  timeout: 30_000,                  // for each test
  expect: { timeout: 5_000 },       // for each assertion
  reporter: 'html',

  use: {
    baseURL: 'https://playwright-playground.com',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },

  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'mobile', use: { ...devices['Pixel 7'] } },
  ],
});

The values for timeout and expect.timeout are the defaults. The CI guide explains the settings that depend on process.env.CI.

Exercises in this guide

More guides