Skip to content

Playwright cheat sheet 2026

144 copy-ready snippets for Playwright 1.64, in TypeScript and Python. Search, or start from the problem you have.

checkout.spec.tstest_checkout.pypassed

Set up & run

7 sections, 41 snippets

CI says the browser executable doesn't exist.--with-deps installs browsers and OS libraries.

New project (TypeScript or JavaScript)
npm init playwright@latestpip install pytest-playwright
playwright install
Add to an existing project
npm install -D @playwright/test
npx playwright installpip install playwright
playwright install
Install one browser
npx playwright install chromiumplaywright install chromium
Browsers + OS libraries (CI images)
npx playwright install --with-depsplaywright install --with-deps
Check the version
npx playwright --versionplaywright --version

The same setup is pasted into every test.describe, beforeEach and named steps.@pytest.fixture and plain test functions.

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

test('has title', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveTitle('Example Domain');
});from playwright.sync_api import Page, expect

def test_has_title(page: Page):
    page.goto("https://example.com")
    expect(page).to_have_title("Example Domain")
Group tests + run code before each
test.describe('checkout', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/cart');
  });

  test('pays by card', async ({ page }) => {
    await page.getByRole('button', { name: 'Pay' }).click();
  });
});import pytest

@pytest.fixture(autouse=True)
def open_cart(page: Page):
    page.goto("/cart")

def test_pays_by_card(page: Page):
    page.get_by_role("button", name="Pay").click()
Named steps in the report
await test.step('add item to cart', async () => {
  await page.getByRole('button', { name: 'Add' }).click();
});await test.step('add item to cart', async () => {
  await page.getByRole('button', { name: 'Add' }).click();
});
Node.js only
Hooks at a glance
test.beforeAll(async () => { /* once per worker */ });
test.beforeEach(async ({ page }) => { /* before every test */ });
test.afterEach(async ({ page }) => { /* after every test */ });
test.afterAll(async () => { /* once per worker */ });test.beforeAll(async () => { /* once per worker */ });
test.beforeEach(async ({ page }) => { /* before every test */ });
test.afterEach(async ({ page }) => { /* after every test */ });
test.afterAll(async () => { /* once per worker */ });
Node.js only

beforeAll / afterAll run once per worker process.

You need a quick script, not a test suite.use the playwright library on its own.

Launch → page → close
import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  console.log(await page.title());
  await browser.close();
})();from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://example.com")
    print(page.title())
    browser.close()

The `playwright` package on its own: for crawlers, scrapers and one-off scripts.

Base URL and browsers repeated in every file.one config file with projects.

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

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 4 : undefined,
  reporter: 'html',
  use: {
    baseURL: 'https://example.com',
    headless: true,
    viewport: { width: 1280, height: 720 },
    trace: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } },
  ],
});# pytest.ini
[pytest]
addopts = --base-url https://example.com --browser chromium --browser firefox --tracing retain-on-failure
Start the app before tests
webServer: {
  command: 'npm run start',
  url: 'http://localhost:3000',
  reuseExistingServer: !process.env.CI,
}webServer: {
  command: 'npm run start',
  url: 'http://localhost:3000',
  reuseExistingServer: !process.env.CI,
}
Node.js only
Assertion timeout
expect: { timeout: 5_000 }expect.set_options(timeout=5_000)
Keep a project out of the default run
projects: [
  { name: 'chromium', use: devices['Desktop Chrome'] },
  { name: 'firefox', use: devices['Desktop Firefox'], default: false },
]projects: [
  { name: 'chromium', use: devices['Desktop Chrome'] },
  { name: 'firefox', use: devices['Desktop Firefox'], default: false },
]
Node.js only

Playwright 1.64+. npx playwright test runs chromium only; --project=firefox or --project="*" runs the rest.

Store screenshots as WebP
expect: { toHaveScreenshot: { type: 'webp' } }expect: { toHaveScreenshot: { type: 'webp' } }
Node.js only

Playwright 1.64+, for screenshots you don't name yourself.

One known bug keeps the whole run red.fixme, fail, skip and tags.skip, xfail and markers.

Skip (always or on a condition)
test.skip(browserName === 'webkit', 'Not supported on WebKit');@pytest.mark.skip_browser("webkit")
def test_upload(page: Page): ...

Inside the test body; browserName comes from the fixtures.

Known bug / expected failure
test.fixme();   // not run, marked as fixme
test.fail();    // runs, must fail@pytest.mark.skip(reason="known bug")
def test_known_bug(page: Page): ...

@pytest.mark.xfail(reason="expected failure")
def test_expected_failure(page: Page): ...
Slow test (triple the timeout)
test.slow();test.slow();
Node.js only
Tag and link an issue
test('checkout', {
  tag: '@smoke',
  annotation: { type: 'issue', description: 'https://jira.example.com/QA-42' },
}, async ({ page }) => { /* … */ });@pytest.mark.smoke
def test_checkout(page: Page): ...
Log in once for a file
test.use({ storageState: 'playwright/.auth/user.json' });@pytest.fixture
def browser_context_args(browser_context_args):
    return {**browser_context_args, "storage_state": "playwright/.auth/user.json"}

test.use goes at file or describe level.

Run tests in a file in order
test.describe.configure({ mode: 'serial' });test.describe.configure({ mode: 'serial' });
Node.js only
Never run these tests at the same time
test.describe.configure({ lock: 'user-settings' });test.describe.configure({ lock: 'user-settings' });
Node.js only

Playwright 1.64+ for a whole file or group. For one test (1.63+): test('…', { lock: 'user-settings' }, async ({ page }) => { … }).

Re-running the whole suite to check one fix.--last-failed, --grep, --only-changed.--lf, -m smoke, -n 4.

Run all tests
npx playwright testpytest
One file
npx playwright test tests/login.spec.tspytest tests/test_login.py
By tag or title
npx playwright test --grep @smokepytest -m smoke
One browser project
npx playwright test --project=firefoxpytest --browser firefox
Watch the browser
npx playwright test --headedpytest --headed
Step through with the Inspector
npx playwright test --debugPWDEBUG=1 pytest -s
Pause inside a test
await page.pause();page.pause()
Re-run only the failures
npx playwright test --last-failedpytest --lf
Only tests changed since main
npx playwright test --only-changed=mainnpx playwright test --only-changed=main
Node.js only
Parallel workers
npx playwright test --workers=4pytest -n 4  # pytest-xdist
Split across CI machines
npx playwright test --shard=1/4npx playwright test --shard=1/4
Node.js only
Random order (find order-dependent tests)
npx playwright test --shuffle
npx playwright test --shuffle 271828182   # replay that seednpx playwright test --shuffle
npx playwright test --shuffle 271828182   # replay that seed
Node.js only

Playwright 1.64+. The run prints its seed so a failing order can be reproduced.

HTML report
npx playwright show-reportnpx playwright show-report
Node.js only
Record a test (codegen)
npx playwright codegen https://example.complaywright codegen https://example.com
AI test agents (planner, generator, healer)
npx playwright init-agents --loop=claudenpx playwright init-agents --loop=claude
Node.js only

Playwright 1.56+. Use --loop=vscode, codex or opencode for other tools. The planner writes a test plan, the generator turns it into tests, the healer fixes failing ones.

A terminal round-trip for every re-run.UI mode with watch and time travel.

Open UI mode
npx playwright test --uinpx playwright test --ui
Node.js only

UI mode is part of the Node.js test runner.

Run tests
F5F5
Node.js only
Stop running tests
Shift + F5Shift + F5
Node.js only
Toggle test output
Ctrl + `Ctrl + `
Node.js only

Find & act

8 sections, 42 snippets

A redesign renamed the classes and half the suite went red.locate by role, text and label, like a user.

Which locator to reach for

First choice

Last resort

The order follows the Playwright docs: what the user sees first, test ids when that is not enough, CSS and XPath last.
By role (first choice)
page.getByRole('button', { name: 'Submit' })page.get_by_role("button", name="Submit")
By text (substring, case-insensitive)
page.getByText('Welcome')
page.getByText('Welcome back', { exact: true })page.get_by_text("Welcome")
page.get_by_text("Welcome back", exact=True)
By label
page.getByLabel('Email')page.get_by_label("Email")
By placeholder
page.getByPlaceholder('Search')page.get_by_placeholder("Search")
By test id (data-testid)
page.getByTestId('login-btn')page.get_by_test_id("login-btn")
By alt text / title
page.getByAltText('Logo')
page.getByTitle('Close')page.get_by_alt_text("Logo")
page.get_by_title("Close")
CSS / XPath
page.locator('.btn-primary')
page.locator('#login')
page.locator('input[name="email"]')
page.locator('//button[@type="submit"]')page.locator(".btn-primary")
page.locator("#login")
page.locator("input[name='email']")
page.locator("//button[@type='submit']")

For elements with nothing user-facing to target.

Filter by text or by a child
page.getByRole('listitem').filter({ hasText: 'Product 2' })
page.getByRole('row').filter({ has: page.getByRole('cell', { name: 'Ada' }) })page.get_by_role("listitem").filter(has_text="Product 2")
page.get_by_role("row").filter(has=page.get_by_role("cell", name="Ada"))
Chain inside a container
page.getByRole('dialog').getByRole('button', { name: 'OK' })page.get_by_role("dialog").get_by_role("button", name="OK")
Pick one of many
page.getByRole('listitem').first()
page.getByRole('listitem').nth(2)
page.getByRole('listitem').last()page.get_by_role("listitem").first
page.get_by_role("listitem").nth(2)
page.get_by_role("listitem").last
Only visible matches
page.locator('.toast').visible()page.locator(".toast").filter(visible=True)

Playwright 1.63+. Same result: .filter({ visible: true }).

This locator, inside that one
const save = page.getByRole('button', { name: 'Save' });
const dialog = page.getByTestId('settings-dialog');
await save.within(dialog).click();const save = page.getByRole('button', { name: 'Save' });
const dialog = page.getByTestId('settings-dialog');
await save.within(dialog).click();
Node.js only

Playwright 1.64+. nth() and first() resolve inside each parent: page.getByRole('cell').nth(2).within(page.getByRole('row')) is the third cell of every row.

By aria ref from an AI snapshot
page.getByRef('e2')page.getByRef('e2')
Node.js only

Playwright 1.64+. The ref comes from page.ariaSnapshot() in 'ai' mode, the snapshot coding agents read.

sleep(3000) before every click, and it is still flaky.actions wait until the element is ready.

What a click waits for
  1. Visiblehas a size, not visibility: hidden
  2. Stablesame box for two animation frames
  3. Receives eventsnot covered by another element
  4. Enablednot disabled
  5. click()only now Playwright clicks
If a check keeps failing, Playwright retries until the action timeout and then throws TimeoutError. No sleeps needed.
Click / double / right click
await locator.click();
await locator.dblclick();
await locator.click({ button: 'right' });locator.click()
locator.dblclick()
locator.click(button="right")
Type into a field (replaces the value)
await page.getByLabel('Username').fill('testuser');page.get_by_label("Username").fill("testuser")
Clear a field
await page.getByLabel('Search').clear();page.get_by_label("Search").clear()
Type key by key (autocomplete, masks)
await locator.pressSequentially('Kyiv', { delay: 50 });locator.press_sequentially("Kyiv", delay=50)
Press a key / shortcut
await page.getByLabel('Search').press('Enter');
await page.keyboard.press('Control+A');page.get_by_label("Search").press("Enter")
page.keyboard.press("Control+A")
Checkbox / radio
await page.getByLabel('I agree').check();
await page.getByLabel('I agree').uncheck();
await page.getByLabel('Express delivery').setChecked(true);page.get_by_label("I agree").check()
page.get_by_label("I agree").uncheck()
page.get_by_label("Express delivery").set_checked(True)
Select from a <select>
await page.getByLabel('Country').selectOption('UA');
await page.getByLabel('Tags').selectOption(['qa', 'e2e']);page.get_by_label("Country").select_option("UA")
page.get_by_label("Tags").select_option(["qa", "e2e"])
Hover
await page.getByRole('menuitem', { name: 'Settings' }).hover();page.get_by_role("menuitem", name="Settings").hover()
Drag and drop
await page.locator('#card').dragTo(page.locator('#done'));page.locator("#card").drag_to(page.locator("#done"))
Scroll into view / focus
await locator.scrollIntoViewIfNeeded();
await locator.focus();locator.scroll_into_view_if_needed()
locator.focus()

The payment form sits in an iframe, so nothing is found.frameLocator() or contentFrame().frame_locator() or content_frame.

Work inside an iframe
const frame = page.frameLocator('#payment');
await frame.getByLabel('Card number').fill('4242 4242 4242 4242');frame = page.frame_locator("#payment")
frame.get_by_label("Card number").fill("4242 4242 4242 4242")
Iframe from an existing locator
await page.locator('iframe[name="editor"]').contentFrame().getByRole('textbox').fill('Hi');page.locator("iframe[name='editor']").content_frame.get_by_role("textbox").fill("Hi")
Search every frame at once
await page.frameLocator().getByRole('button', { name: 'Pay' }).click();await page.frameLocator().getByRole('button', { name: 'Pay' }).click();
Node.js only

Playwright 1.63+: without a selector it searches all frames in the page.

confirm() is dismissed on its own, so Delete never happens.register a dialog handler before the click.

Accept an alert / confirm
page.once('dialog', (dialog) => dialog.accept());
await page.getByRole('button', { name: 'Delete' }).click();page.once("dialog", lambda dialog: dialog.accept())
page.get_by_role("button", name="Delete").click()

Register the handler before the click. Without a handler, dialogs are dismissed automatically.

Dismiss a confirm
page.once('dialog', (dialog) => dialog.dismiss());page.once("dialog", lambda dialog: dialog.dismiss())
Answer a prompt
page.once('dialog', (dialog) => dialog.accept('Ada'));page.once("dialog", lambda dialog: dialog.accept("Ada"))
Check the message
page.once('dialog', async (dialog) => {
  expect(dialog.message()).toContain('Are you sure?');
  await dialog.accept();
});def handle(dialog):
    assert "Are you sure?" in dialog.message
    dialog.accept()

page.once("dialog", handle)

Waiting for the new tab after the click just hangs.start waiting before the click.

Start waiting before the click

Wait after the clickThe event has already fired.

  1. click()opens the new tab
  2. 'popup' eventfires, nobody is listening
  3. waitForEvent('popup')wait_for_event("popup")starts listening too late
  4. Timeoutthe test fails

Arm, then clickThe event is caught.

  1. waitForEvent('popup')with expect_popup()armed, not awaited yetarmed for the block
  2. click()opens the new tab
  3. 'popup' eventcaught
  4. await popupPromiseinfo.valuethe new page, ready to use
Same rule for waitForEvent('download'), waitForEvent('filechooser') and waitForResponse().Same rule for expect_download(), expect_file_chooser() and expect_response().
Link that opens a new tab
const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'Open docs' }).click();
const popup = await popupPromise;
await expect(popup).toHaveTitle(/Docs/);with page.expect_popup() as popup_info:
    page.get_by_role("link", name="Open docs").click()
popup = popup_info.value
expect(popup).to_have_title(re.compile("Docs"))

Start waiting before the click.

Any new tab in the context
const pagePromise = context.waitForEvent('page');
await page.getByRole('button', { name: 'Open report' }).click();
const newPage = await pagePromise;with context.expect_page() as page_info:
    page.get_by_role("button", name="Open report").click()
new_page = page_info.value
All open tabs / switch
const pages = context.pages();
await pages[1].bringToFront();pages = context.pages
pages[1].bring_to_front()

The native file picker can't be scripted.setInputFiles(), or catch the file chooser.set_input_files(), or catch the file chooser.

Upload one file
await page.getByLabel('Upload CV').setInputFiles('fixtures/cv.pdf');page.get_by_label("Upload CV").set_input_files("fixtures/cv.pdf")
Upload several / clear
await page.getByLabel('Photos').setInputFiles(['a.png', 'b.png']);
await page.getByLabel('Photos').setInputFiles([]);page.get_by_label("Photos").set_input_files(["a.png", "b.png"])
page.get_by_label("Photos").set_input_files([])
File from memory
await page.getByLabel('Upload').setInputFiles({
  name: 'data.csv',
  mimeType: 'text/csv',
  buffer: Buffer.from('id,name\n1,Ada'),
});page.get_by_label("Upload").set_input_files(
    files=[{"name": "data.csv", "mimeType": "text/csv", "buffer": b"id,name\n1,Ada"}]
)
Upload button without an <input>
const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Upload' }).click();
const chooser = await chooserPromise;
await chooser.setFiles('fixtures/cv.pdf');with page.expect_file_chooser() as fc_info:
    page.get_by_role("button", name="Upload").click()
fc_info.value.set_files("fixtures/cv.pdf")

The exported file disappears with the context.saveAs() to a path you control.save_as() to a path you control.

Wait for and save a download
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export' }).click();
const download = await downloadPromise;
await download.saveAs('downloads/' + download.suggestedFilename());with page.expect_download() as info:
    page.get_by_role("button", name="Export").click()
download = info.value
download.save_as("downloads/" + download.suggested_filename)
Temporary path of the file
const filePath = await download.path();file_path = download.path()

Assert & debug

5 sections, 31 snippets

The check ran once and the UI was a moment late.expect() retries until it passes or times out.

Checked once vs re-checked

Checked onceexpect(await el.isVisible()).toBe(true)assert el.is_visible()

'Saved' shows up
fails at once

Web-first assertionawait expect(el).toBeVisible()expect(el).to_be_visible()

passes
Web-first assertions keep re-checking until they pass or the timeout runs out (5 s by default, expect: { timeout } in the configchange it with expect.set_options(timeout=…)).
Visible / hidden
await expect(locator).toBeVisible();
await expect(locator).toBeHidden();expect(locator).to_be_visible()
expect(locator).to_be_hidden()
Exact / partial text
await expect(locator).toHaveText('Welcome, Ada');
await expect(locator).toContainText('Welcome');expect(locator).to_have_text("Welcome, Ada")
expect(locator).to_contain_text("Welcome")
Input value
await expect(page.getByLabel('Email')).toHaveValue('ada@example.com');expect(page.get_by_label("Email")).to_have_value("ada@example.com")
Attribute / class
await expect(link).toHaveAttribute('href', '/home');
await expect(tab).toHaveClass(/active/);expect(link).to_have_attribute("href", "/home")
expect(tab).to_have_class(re.compile("active"))
Enabled / disabled / checked
await expect(button).toBeEnabled();
await expect(button).toBeDisabled();
await expect(checkbox).toBeChecked();expect(button).to_be_enabled()
expect(button).to_be_disabled()
expect(checkbox).to_be_checked()
Count of matches
await expect(page.getByRole('listitem')).toHaveCount(3);expect(page.get_by_role("listitem")).to_have_count(3)
Page URL and title
await expect(page).toHaveURL(/\/dashboard/);
await expect(page).toHaveTitle('Dashboard');expect(page).to_have_url(re.compile("/dashboard"))
expect(page).to_have_title("Dashboard")
Accessibility tree snapshot
await expect(page.getByRole('navigation')).toMatchAriaSnapshot(`
  - link "Home"
  - link "Pricing"
`);expect(page.get_by_role("navigation")).to_match_aria_snapshot("""
  - link "Home"
  - link "Pricing"
""")
Visual comparison
await expect(page).toHaveScreenshot('home.png');await expect(page).toHaveScreenshot('home.png');
Node.js only
Soft assertion (test keeps going)
await expect.soft(locator).toHaveText('Saved');await expect.soft(locator).toHaveText('Saved');
Node.js only
Negate / longer timeout
await expect(spinner).not.toBeVisible({ timeout: 10_000 });expect(spinner).not_to_be_visible(timeout=10_000)

Fixed sleeps make the suite slow and still flaky.wait for a URL, a response or a state.

Wait for an element
await expect(page.getByText('Saved')).toBeVisible();expect(page.get_by_text("Saved")).to_be_visible()

Actions and expect() wait automatically: no sleeps needed.

Wait until it disappears
await page.getByTestId('spinner').waitFor({ state: 'hidden' });page.get_by_test_id("spinner").wait_for(state="hidden")
Wait for a URL after a click
await page.getByRole('button', { name: 'Next' }).click();
await page.waitForURL('**/step-2');page.get_by_role("button", name="Next").click()
page.wait_for_url("**/step-2")
Wait for a network response
const responsePromise = page.waitForResponse('**/api/data');
await page.getByRole('button', { name: 'Load' }).click();
const response = await responsePromise;
expect(response.status()).toBe(200);with page.expect_response("**/api/data") as info:
    page.get_by_role("button", name="Load").click()
assert info.value.status == 200

Start waiting before the click: no await on the first line.

Wait for a load state
await page.waitForLoadState('domcontentloaded');page.wait_for_load_state("domcontentloaded")
Retry a block until it passes
await expect(async () => {
  const res = await page.request.get('/api/status');
  expect(res.status()).toBe(200);
}).toPass({ timeout: 15_000 });await expect(async () => {
  const res = await page.request.get('/api/status');
  expect(res.status()).toBe(200);
}).toPass({ timeout: 15_000 });
Node.js only
Default timeouts
page.setDefaultTimeout(10_000);            // actions
page.setDefaultNavigationTimeout(30_000); // goto, waitForURLpage.set_default_timeout(10_000)
page.set_default_navigation_timeout(30_000)

A page breaks and you never see its console errors.listen to console, read title and URL.

Title, URL, HTML
const title = await page.title();
const url = page.url();
const html = await page.content();title = page.title()
url = page.url
html = page.content()
Viewport size
const size = page.viewportSize();size = page.viewport_size
Browser console messages
page.on('console', (msg) => console.log(msg.type(), msg.text()));page.on("console", lambda msg: print(msg.type, msg.text))

A CI failure with no idea what was on screen.keep screenshots and video on failure.

Screenshot (viewport / full page)
await page.screenshot({ path: 'page.png' });
await page.screenshot({ path: 'full.png', fullPage: true });page.screenshot(path="page.png")
page.screenshot(path="full.png", full_page=True)
Screenshot one element
await page.getByRole('dialog').screenshot({ path: 'dialog.png' });page.get_by_role("dialog").screenshot(path="dialog.png")
Hide changing parts
await page.screenshot({ path: 'stable.png', mask: [page.getByTestId('clock')] });page.screenshot(path="stable.png", mask=[page.get_by_test_id("clock")])
Keep artifacts of failed tests (config)
use: { video: 'retain-on-failure', screenshot: 'only-on-failure' }pytest --video=retain-on-failure --screenshot=only-on-failure
Record video in a script
const context = await browser.newContext({ recordVideo: { dir: 'videos/' } });context = browser.new_context(record_video_dir="videos/")
Video size and frame rate (config)
use: { video: { mode: 'on', size: { width: 1920, height: 1080 }, fps: 60 } }use: { video: { mode: 'on', size: { width: 1920, height: 1080 }, fps: 60 } }
Node.js only

Playwright 1.64+. Firefox and WebKit capture up to 25 fps; videos are now encoded as VP9.

Fails in CI, passes on your laptop.record a trace and open it in Trace Viewer.

From a red test to the reason
  1. trace: 'on-first-retry'--tracing=retain-on-failurerecords a trace when a test is retriedkeeps the trace when a test fails
  2. trace.zipretry #1 fails, the trace is savedthe test fails, the trace is kept
  3. npx playwright show-traceplaywright show-traceopens Trace Viewer
  1. goto /checkout
  2. fill Card number
  3. click Pay
  4. expect Paid
Snapshot at the failing stepPayment declined: card expired
Trace Viewer shows every action with a DOM snapshot, network calls and console output, so the failing step explains itself.
Trace on the first retry (config)
use: { trace: 'on-first-retry' }pytest --tracing=retain-on-failure
Force a trace for one run
npx playwright test --trace onpytest --tracing=on
Record a trace in a script
await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
// … steps …
await context.tracing.stop({ path: 'trace.zip' });context.tracing.start(screenshots=True, snapshots=True, sources=True)
# … steps …
context.tracing.stop(path="trace.zip")
Open a trace
npx playwright show-trace trace.zipplaywright show-trace trace.zip

Context & network

6 sections, 30 snippets

An admin and a user must act in one test.two isolated contexts in one browser.

Launch a browser (visible, slowed down)
const browser = await chromium.launch({ headless: false, slowMo: 250 });browser = p.chromium.launch(headless=False, slow_mo=250)
New isolated context (like incognito)
const context = await browser.newContext({ viewport: { width: 1280, height: 720 }, locale: 'en-GB' });context = browser.new_context(viewport={"width": 1280, "height": 720}, locale="en-GB")
New page (tab) in the context
const page = await context.newPage();page = context.new_page()
Two users side by side
const admin = await browser.newContext({ storageState: 'auth/admin.json' });
const user = await browser.newContext({ storageState: 'auth/user.json' });admin = browser.new_context(storage_state="auth/admin.json")
user = browser.new_context(storage_state="auth/user.json")
Close
await context.close();
await browser.close();context.close()
browser.close()

A test has to start with a specific cookie.addCookies() and clearCookies() on the context.add_cookies() and clear_cookies() on the context.

Get cookies
const cookies = await context.cookies();cookies = context.cookies()
Set a cookie
await context.addCookies([
  { name: 'token', value: 'abc123', domain: 'example.com', path: '/' },
]);context.add_cookies([
    {"name": "token", "value": "abc123", "domain": "example.com", "path": "/"}
])
Clear all / one cookie
await context.clearCookies();
await context.clearCookies({ name: 'token' });context.clear_cookies()
context.clear_cookies(name="token")

Every test spends seconds on the login form.save storageState once and reuse it.save storage_state once and reuse it.

Log in once, reuse the state
Log in onceauth.setup.tsconftest.py fixture
playwright/.auth/user.jsoncookies + localStorage
  • checkout.spec.tstest_checkout.py
  • cart.spec.tstest_cart.py
  • orders.spec.tstest_orders.py
  • profile.spec.tstest_profile.py
  • search.spec.tstest_search.py
  • settings.spec.tstest_settings.py
Every test starts with the saved cookies and localStorage instead of the login form. Estimate the time it saves with the storageState calculator.
Set / read localStorage
await page.localStorage.setItem('theme', 'dark');
const theme = await page.localStorage.getItem('theme');page.evaluate("localStorage.setItem('theme', 'dark')")
theme = page.evaluate("localStorage.getItem('theme')")

Playwright 1.61+, for the page's current origin.

Set / read sessionStorage
await page.sessionStorage.setItem('step', '2');
const step = await page.sessionStorage.getItem('step');page.evaluate("sessionStorage.setItem('step', '2')")
step = page.evaluate("sessionStorage.getItem('step')")
Clear localStorage
await page.localStorage.clear();page.evaluate("localStorage.clear()")
Save the logged-in state
await context.storageState({ path: 'playwright/.auth/user.json' });context.storage_state(path="playwright/.auth/user.json")

Saves cookies and localStorage (IndexedDB with indexedDB: true). sessionStorage is not included.

Start a context logged in
const context = await browser.newContext({ storageState: 'playwright/.auth/user.json' });context = browser.new_context(storage_state="playwright/.auth/user.json")

Creating test data through the UI is slow.call the API directly with request.

GET and assert
const response = await request.get('/api/users');
await expect(response).toBeOK();
const json = await response.json();
expect(json.data).toHaveLength(1);api = playwright.request.new_context(base_url="https://api.example.com")
response = api.get("/api/users")
expect(response).to_be_ok()
assert len(response.json()["data"]) == 1
POST JSON
const created = await request.post('/api/users', { data: { name: 'Ada', role: 'qa' } });
expect(created.status()).toBe(201);created = api.post("/api/users", data={"name": "Ada", "role": "qa"})
assert created.status == 201
Client with a token
const api = await playwright.request.newContext({
  baseURL: 'https://api.example.com',
  extraHTTPHeaders: { Authorization: `Bearer ${process.env.API_TOKEN}` },
});api = playwright.request.new_context(
    base_url="https://api.example.com",
    extra_http_headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"},
)
Same cookies as the page
const res = await page.request.get('/api/profile');res = page.request.get("/api/profile")

page.request shares cookies with the browser context.

Cookies of a request context
await request.addCookies([{ name: 'session-id', value: '42', url: 'https://example.com' }]);
console.log(await request.cookies('https://example.com'));
await request.clearCookies({ name: 'session-id' });await request.addCookies([{ name: 'session-id', value: '42', url: 'https://example.com' }]);
console.log(await request.cookies('https://example.com'));
await request.clearCookies({ name: 'session-id' });
Node.js only

Playwright 1.64+, mirroring the BrowserContext cookie methods.

The staging API is down, or a 500 is hard to reproduce.page.route() mocks, patches or blocks.

One route, three exits
pageGET /api/orders
page.route('**/api/**', handler)page.route("**/api/**", handler)
  1. route.fulfill({ json })route.fulfill(json=data)mock data, the server is never called
  2. route.continue({ headers })route.continue_(headers=headers)goes to the server, changed on the way
  3. route.abort()blocked, so you can test the error state
Register the route before the page sends the request, for example before page.goto().
Mock a response
await page.route('**/api/users', (route) =>
  route.fulfill({ status: 200, json: [{ id: 1, name: 'Mock' }] }),
);page.route("**/api/users", lambda route: route.fulfill(status=200, json=[{"id": 1, "name": "Mock"}]))
Patch a real response
await page.route('**/api/users', async (route) => {
  const response = await route.fetch();
  const json = await response.json();
  json.push({ id: 99, name: 'Injected' });
  await route.fulfill({ response, json });
});def handle(route):
    response = route.fetch()
    data = response.json()
    data.append({"id": 99, "name": "Injected"})
    route.fulfill(response=response, json=data)

page.route("**/api/users", handle)
Add a request header
await page.route('**/api/**', (route) =>
  route.continue({ headers: { ...route.request().headers(), 'x-test': '1' } }),
);page.route("**/api/**", lambda route: route.continue_(headers={**route.request.headers, "x-test": "1"}))
Simulate a server error
await page.route('**/api/orders', (route) => route.fulfill({ status: 500 }));page.route("**/api/orders", lambda route: route.fulfill(status=500))
Block images
await page.route(/\.(png|jpg|webp)$/, (route) => route.abort());page.route(re.compile(r"\.(png|jpg|webp)$"), lambda route: route.abort())
Replay the API from a HAR file
await page.routeFromHAR('hars/api.har', { url: '**/api/**', update: false });page.route_from_har("hars/api.har", url="**/api/**", update=False)

Run once with update: true to record the real responses, then replay them offline.

A bug shows up only on a phone, in dark mode, in another time zone.emulate the device, color scheme, locale and clock.

Set the viewport
await page.setViewportSize({ width: 1280, height: 720 });page.set_viewport_size({"width": 1280, "height": 720})
Emulate a phone (config)
// playwright.config.ts → projects
{ name: 'mobile', use: { ...devices['iPhone 15'] } }pytest --device="iPhone 15"

Since 1.64 device descriptors also set screen, so window.screen and media queries see the emulated size. Add screen: undefined to opt out.

Dark mode / reduced motion
await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' });page.emulate_media(color_scheme="dark", reduced_motion="reduce")
Locale, time zone, user agent
test.use({ locale: 'uk-UA', timezoneId: 'Europe/Kyiv', userAgent: 'MyTestBot/1.0' });context = browser.new_context(locale="uk-UA", timezone_id="Europe/Kyiv", user_agent="MyTestBot/1.0")

At file or describe level, or in the config's use block.

Geolocation
await context.grantPermissions(['geolocation']);
await context.setGeolocation({ latitude: 50.45, longitude: 30.52 });context.grant_permissions(["geolocation"])
context.set_geolocation({"latitude": 50.45, "longitude": 30.52})
Freeze the clock
await page.clock.setFixedTime(new Date('2026-12-31T23:59:00'));page.clock.set_fixed_time(datetime.datetime(2026, 12, 31, 23, 59))

Download the poster

The lines you type every day on one sheet: commands, locators, actions, assertions, mocking, plus the locator order and the six most common problems. Free PNG for your team chat, wiki or the wall by your desk.

AQAPro Playwright cheat sheet poster: locator priority order, six common problems with their fixes, and everyday TypeScript lines for setup and CLI, locators and actions, assertions and debugging, context and network mocking.

FAQ

What is the recommended locator in Playwright?

getByRole with an accessible name, e.g. page.getByRole('button', { name: 'Submit' }). Then getByLabel, getByPlaceholder, getByText and getByTestId. Use CSS or XPath for elements with nothing user-facing to target.

Do I need explicit waits in Playwright?

Rarely. Actions wait until the element is visible, stable, enabled and able to receive the click, and expect() assertions retry until they pass or time out. Use waitForURL, waitForResponse or locator.waitFor for the few cases an assertion can't express.

How do I handle a new tab or popup in Playwright?

Start waiting before the click: const popupPromise = page.waitForEvent('popup'); click the link; then const popup = await popupPromise. In Python use with page.expect_popup() as popup_info. The popup is a normal page you can assert on.

How do I open a Playwright trace?

Set trace: 'on-first-retry' in the config (or run with --trace on), then open the HTML report with npx playwright show-report and click the trace, or run npx playwright show-trace path/to/trace.zip.

Does this cheat sheet cover Python?

Yes: switch the language toggle to Python. The sync API with pytest-playwright uses snake_case names (get_by_role, to_have_text) and context managers such as page.expect_popup() where TypeScript uses promises. UI mode and its shortcuts belong to the Node.js test runner.