Playwright cheat sheet 2026
144 copy-ready snippets for Playwright 1.64, in TypeScript and Python. Search, or start from the problem you have.
auto-waitauto-waitBroke after a redesigngetByRoleget_by_roleNew tab not caughtwait firstexpect_popupLogin in every teststorageStatestorage_stateBackend not readypage.routepage.routeFails only in CItracetracingSet up & run
7 sections, 41 snippets
CI says the browser executable doesn't exist.--with-deps installs browsers and OS libraries.
npm init playwright@latestpip install pytest-playwright playwright install
npm install -D @playwright/test npx playwright installpip install playwright playwright install
npx playwright install chromiumplaywright install chromium
npx playwright install --with-depsplaywright install --with-deps
npx playwright --versionplaywright --version
The same setup is pasted into every test.describe, beforeEach and named steps.@pytest.fixture and plain test functions.
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")
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()
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(); });
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 */ });
beforeAll / afterAll run once per worker process.
You need a quick script, not a test suite.use the playwright library on its own.
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.
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
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, }
expect: { timeout: 5_000 }expect.set_options(timeout=5_000)
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 }, ]
Playwright 1.64+. npx playwright test runs chromium only; --project=firefox or --project="*" runs the rest.
expect: { toHaveScreenshot: { type: 'webp' } }expect: { toHaveScreenshot: { type: 'webp' } }
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.
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.
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): ...
test.slow();test.slow();
test('checkout', { tag: '@smoke', annotation: { type: 'issue', description: 'https://jira.example.com/QA-42' }, }, async ({ page }) => { /* … */ });@pytest.mark.smoke def test_checkout(page: Page): ...
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.
test.describe.configure({ mode: 'serial' });test.describe.configure({ mode: 'serial' });
test.describe.configure({ lock: 'user-settings' });test.describe.configure({ lock: 'user-settings' });
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.
npx playwright testpytest
npx playwright test tests/login.spec.tspytest tests/test_login.py
npx playwright test --grep @smokepytest -m smoke
npx playwright test --project=firefoxpytest --browser firefox
npx playwright test --headedpytest --headed
npx playwright test --debugPWDEBUG=1 pytest -s
await page.pause();page.pause()
npx playwright test --last-failedpytest --lf
npx playwright test --only-changed=mainnpx playwright test --only-changed=main
npx playwright test --workers=4pytest -n 4 # pytest-xdist
npx playwright test --shard=1/4npx playwright test --shard=1/4
npx playwright test --shuffle npx playwright test --shuffle 271828182 # replay that seednpx playwright test --shuffle npx playwright test --shuffle 271828182 # replay that seed
Playwright 1.64+. The run prints its seed so a failing order can be reproduced.
npx playwright show-reportnpx playwright show-report
npx playwright codegen https://example.complaywright codegen https://example.com
npx playwright init-agents --loop=claudenpx playwright init-agents --loop=claude
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.
npx playwright test --uinpx playwright test --ui
UI mode is part of the Node.js test runner.
F5F5
Shift + F5Shift + F5
Ctrl + `Ctrl + `
Find & act
8 sections, 42 snippets
Locators
13A redesign renamed the classes and half the suite went red.locate by role, text and label, like a user.
First choice
Last resort
page.getByRole('button', { name: 'Submit' })page.get_by_role("button", name="Submit")
page.getByText('Welcome') page.getByText('Welcome back', { exact: true })page.get_by_text("Welcome") page.get_by_text("Welcome back", exact=True)
page.getByLabel('Email')page.get_by_label("Email")
page.getByPlaceholder('Search')page.get_by_placeholder("Search")
page.getByTestId('login-btn')page.get_by_test_id("login-btn")
page.getByAltText('Logo') page.getByTitle('Close')page.get_by_alt_text("Logo") page.get_by_title("Close")
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.
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"))
page.getByRole('dialog').getByRole('button', { name: 'OK' })page.get_by_role("dialog").get_by_role("button", name="OK")
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
page.locator('.toast').visible()page.locator(".toast").filter(visible=True)
Playwright 1.63+. Same result: .filter({ visible: true }).
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();
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.
page.getByRef('e2')page.getByRef('e2')
Playwright 1.64+. The ref comes from page.ariaSnapshot() in 'ai' mode, the snapshot coding agents read.
Actions
10sleep(3000) before every click, and it is still flaky.actions wait until the element is ready.
- Visiblehas a size, not visibility: hidden
- Stablesame box for two animation frames
- Receives eventsnot covered by another element
- Enablednot disabled
- click()only now Playwright clicks
TimeoutError. No sleeps needed.await locator.click(); await locator.dblclick(); await locator.click({ button: 'right' });locator.click() locator.dblclick() locator.click(button="right")
await page.getByLabel('Username').fill('testuser');page.get_by_label("Username").fill("testuser")
await page.getByLabel('Search').clear();page.get_by_label("Search").clear()
await locator.pressSequentially('Kyiv', { delay: 50 });locator.press_sequentially("Kyiv", delay=50)
await page.getByLabel('Search').press('Enter'); await page.keyboard.press('Control+A');page.get_by_label("Search").press("Enter") page.keyboard.press("Control+A")
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)
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"])
await page.getByRole('menuitem', { name: 'Settings' }).hover();page.get_by_role("menuitem", name="Settings").hover()
await page.locator('#card').dragTo(page.locator('#done'));page.locator("#card").drag_to(page.locator("#done"))
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.
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")
await page.locator('iframe[name="editor"]').contentFrame().getByRole('textbox').fill('Hi');page.locator("iframe[name='editor']").content_frame.get_by_role("textbox").fill("Hi")
await page.frameLocator().getByRole('button', { name: 'Pay' }).click();await page.frameLocator().getByRole('button', { name: 'Pay' }).click();
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.
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.
page.once('dialog', (dialog) => dialog.dismiss());page.once("dialog", lambda dialog: dialog.dismiss())
page.once('dialog', (dialog) => dialog.accept('Ada'));page.once("dialog", lambda dialog: dialog.accept("Ada"))
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.
Wait after the clickThe event has already fired.
- click()opens the new tab
- 'popup' eventfires, nobody is listening
- waitForEvent('popup')wait_for_event("popup")starts listening too late
- Timeoutthe test fails
Arm, then clickThe event is caught.
- waitForEvent('popup')with expect_popup()armed, not awaited yetarmed for the block
- click()opens the new tab
- 'popup' eventcaught
- await popupPromiseinfo.valuethe new page, ready to use
waitForEvent('download'), waitForEvent('filechooser') and waitForResponse().Same rule for expect_download(), expect_file_chooser() and expect_response().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.
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
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.
await page.getByLabel('Upload CV').setInputFiles('fixtures/cv.pdf');page.get_by_label("Upload CV").set_input_files("fixtures/cv.pdf")
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([])
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"}] )
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.
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)
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 onceexpect(await el.isVisible()).toBe(true)assert el.is_visible()
Web-first assertionawait expect(el).toBeVisible()expect(el).to_be_visible()
expect: { timeout } in the configchange it with expect.set_options(timeout=…)).await expect(locator).toBeVisible(); await expect(locator).toBeHidden();expect(locator).to_be_visible() expect(locator).to_be_hidden()
await expect(locator).toHaveText('Welcome, Ada'); await expect(locator).toContainText('Welcome');expect(locator).to_have_text("Welcome, Ada") expect(locator).to_contain_text("Welcome")
await expect(page.getByLabel('Email')).toHaveValue('ada@example.com');expect(page.get_by_label("Email")).to_have_value("ada@example.com")
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"))
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()
await expect(page.getByRole('listitem')).toHaveCount(3);expect(page.get_by_role("listitem")).to_have_count(3)
await expect(page).toHaveURL(/\/dashboard/); await expect(page).toHaveTitle('Dashboard');expect(page).to_have_url(re.compile("/dashboard")) expect(page).to_have_title("Dashboard")
await expect(page.getByRole('navigation')).toMatchAriaSnapshot(` - link "Home" - link "Pricing" `);expect(page.get_by_role("navigation")).to_match_aria_snapshot(""" - link "Home" - link "Pricing" """)
await expect(page).toHaveScreenshot('home.png');await expect(page).toHaveScreenshot('home.png');
await expect.soft(locator).toHaveText('Saved');await expect.soft(locator).toHaveText('Saved');
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.
await expect(page.getByText('Saved')).toBeVisible();expect(page.get_by_text("Saved")).to_be_visible()
Actions and expect() wait automatically: no sleeps needed.
await page.getByTestId('spinner').waitFor({ state: 'hidden' });page.get_by_test_id("spinner").wait_for(state="hidden")
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")
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.
await page.waitForLoadState('domcontentloaded');page.wait_for_load_state("domcontentloaded")
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 });
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.
const title = await page.title(); const url = page.url(); const html = await page.content();title = page.title() url = page.url html = page.content()
const size = page.viewportSize();size = page.viewport_size
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.
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)
await page.getByRole('dialog').screenshot({ path: 'dialog.png' });page.get_by_role("dialog").screenshot(path="dialog.png")
await page.screenshot({ path: 'stable.png', mask: [page.getByTestId('clock')] });page.screenshot(path="stable.png", mask=[page.get_by_test_id("clock")])
use: { video: 'retain-on-failure', screenshot: 'only-on-failure' }pytest --video=retain-on-failure --screenshot=only-on-failure
const context = await browser.newContext({ recordVideo: { dir: 'videos/' } });context = browser.new_context(record_video_dir="videos/")
use: { video: { mode: 'on', size: { width: 1920, height: 1080 }, fps: 60 } }use: { video: { mode: 'on', size: { width: 1920, height: 1080 }, fps: 60 } }
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.
- trace: 'on-first-retry'--tracing=retain-on-failurerecords a trace when a test is retriedkeeps the trace when a test fails
- trace.zipretry #1 fails, the trace is savedthe test fails, the trace is kept
- npx playwright show-traceplaywright show-traceopens Trace Viewer
- goto /checkout
- fill Card number
- click Pay
- expect Paid
use: { trace: 'on-first-retry' }pytest --tracing=retain-on-failure
npx playwright test --trace onpytest --tracing=on
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")
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.
const browser = await chromium.launch({ headless: false, slowMo: 250 });browser = p.chromium.launch(headless=False, slow_mo=250)
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")
const page = await context.newPage();page = context.new_page()
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")
await context.close(); await browser.close();context.close() browser.close()
Every test spends seconds on the login form.save storageState once and reuse it.save storage_state once and reuse it.
auth.setup.tsconftest.py fixture- 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
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.
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')")
await page.localStorage.clear();page.evaluate("localStorage.clear()")
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.
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.
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
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
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']}"}, )
const res = await page.request.get('/api/profile');res = page.request.get("/api/profile")
page.request shares cookies with the browser 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' });
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.
page.route('**/api/**', handler)page.route("**/api/**", handler)route.fulfill({ json })route.fulfill(json=data)mock data, the server is never calledroute.continue({ headers })route.continue_(headers=headers)goes to the server, changed on the wayroute.abort()blocked, so you can test the error state
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"}]))
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)
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"}))
await page.route('**/api/orders', (route) => route.fulfill({ status: 500 }));page.route("**/api/orders", lambda route: route.fulfill(status=500))
await page.route(/\.(png|jpg|webp)$/, (route) => route.abort());page.route(re.compile(r"\.(png|jpg|webp)$"), lambda route: route.abort())
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.
await page.setViewportSize({ width: 1280, height: 720 });page.set_viewport_size({"width": 1280, "height": 720})
// 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.
await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' });page.emulate_media(color_scheme="dark", reduced_motion="reduce")
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.
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})
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.

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.