Playwright Cheat Sheet

By Syncfusion®, Inc. · Last updated

A one-page reference for the whole course: CLI commands, test structure, locators, actions, assertions, configuration, fixtures, authentication, network mocking, API testing, debugging, reporting and CI, with runnable examples and three review exercises.

What you will learn

  • Find the right Playwright command or API quickly
  • Recall the best-practice choice for locators, waits and assertions
  • Combine UI, network and API features in one test

Playwright Cheat Sheet

  • This page collects the most used commands and APIs from the whole course, in one place.
  • Each section has a short table and a box you can run. The lesson that teaches it in depth is named at the start.
  • Keep it open while you write tests.

Simple lesson: look things up here. Learn them in the lesson named next to each section.

A Real-World Example

  • One test can use almost everything from this course: a logged-in user, a mocked API, locators, actions and web-first assertions.

What You Will Find

Animation: the eight chapters of the course light up one after another, from Foundations to Advanced and AI

Eight chapters, 23 lessons. Each section below points back to the lesson that teaches it.

  1. CLI commands and test structure.
  2. Locators and actions.
  3. Assertions.
  4. Configuration and fixtures.
  5. Authentication, network and API.
  6. Debugging, reporting and CI.

Commands and Structure

CLI Commands

CommandWhat it does
npm init playwright@latestCreate a project
npx playwright install --with-depsInstall browsers and Linux libraries
npx playwright testRun all tests
npx playwright test cart.spec.ts:12Run the test on line 12
--project=chromiumOne project only
-g "@smoke" / --grep-invertFilter by title or tag
--headed, --debug, --uiWatch, step through, or open UI Mode
--workers=2, --shard=1/3Parallel workers, split across machines
--repeat-each=10, --retries=2Hunt flaky tests, retry failures
--trace on, -uRecord traces, update snapshots
--last-failed, --listRerun failures, list tests
npx playwright show-reportOpen the HTML report
npx playwright show-trace trace.zipOpen a trace
npx playwright codegen <url>Record a test

Test Structure

CodeUse
test('title', async ({ page }) => { ... })A test
test.describe('group', () => { ... })Group tests
test.beforeEach / afterEach / beforeAll / afterAllHooks
test.step('name', async () => { ... })Named steps in reports
test.only, test.skip, test.fixme, test.fail, test.slowFocus and annotations
test('title', { tag: '@smoke' }, ...)Tags
test.use({ ... })Options for a file or group

Simple lesson: npx playwright test with flags runs anything. test, describe, hooks and steps shape a file.

Locators and Actions

Locators (best first)

LocatorExample
Role and namepage.getByRole('button', { name: 'Log in' })
Labelpage.getByLabel('Email')
Placeholderpage.getByPlaceholder('Search by name')
Textpage.getByText('Your cart is empty')
Alt text, titlepage.getByAltText('Steel water bottle'), page.getByTitle('...')
Test idpage.getByTestId('cart-count')
CSS (last resort)page.locator('.price')
Filter.filter({ hasText: 'Yoga Mat' }), .filter({ has: locator })
Chaincard.getByRole('button', { name: 'Add to cart' })
Pick one.first(), .last(), .nth(2)
Framespage.frameLocator('iframe[name="payment"]').getByLabel('Card number')

Actions

ActionExample
Click.click(), .dblclick(), .click({ button: 'right' })
Type.fill('text'), .pressSequentially('abc'), .clear()
Keys.press('Enter'), page.keyboard.press('Control+K')
Choose.check(), .uncheck(), .selectOption('Shoes')
Other.hover(), .focus(), .dragTo(target), .setInputFiles(path)

Simple lesson: prefer roles, labels and test ids. Filter and chain to reach one element.

Assertions

Web-First Assertions (they retry)

Page or locator checkExample
Visible, hiddentoBeVisible(), toBeHidden()
Enabled, checked, focusedtoBeEnabled(), toBeChecked(), toBeFocused()
TexttoHaveText('...'), toContainText('...'), toHaveText([...])
Count, value, attributetoHaveCount(3), toHaveValue('...'), toHaveAttribute('href', '/cart')
PagetoHaveURL('/account'), toHaveTitle(/Shop/)
Structure, looktoMatchAriaSnapshot(...), toHaveScreenshot('x.png')
API responseawait expect(response).toBeOK()
  • Always await them. Plain value checks (toBe, toEqual, toContain) do not retry.
  • expect.soft() keeps going after a failure. expect.poll() and toPass() retry your own code.

expect(await locator.textContent()).toBe('...') reads once and does not retry. Write await expect(locator).toHaveText('...') instead.

Configuration and Fixtures

Config Options You Will Use

OptionExample
Where tests livetestDir: './tests'
Server and timeoutsuse: { baseURL, actionTimeout: 5_000 }, timeout: 30_000, expect: { timeout: 5_000 }
CI behaviourforbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0, workers
Debug datause: { trace: 'on-first-retry', screenshot: 'only-on-failure', video: 'retain-on-failure' }
Browsers and devicesprojects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }]
Setup first{ name: 'setup', testMatch: /.*\.setup\.ts/ }, dependencies: ['setup']
Reportsreporter: [['list'], ['html', { open: 'never' }]]
Start the appwebServer: { command: 'npm start', url: 'http://localhost:3000' }

Fixtures

export const test = base.extend<{ cartPage: CartPage }>({
  cartPage: async ({ page }, use) => {
    const cartPage = new CartPage(page); // setup
    await use(cartPage);                // the test runs here
    // teardown goes after use()
  },
});
  • Built-in fixtures: page, context, browser, request, browserName, baseURL.
  • { scope: 'worker' } shares one value per worker. { auto: true } runs without being asked for.

Simple lesson: the config sets defaults for every test. Fixtures give each test what it needs.

Authentication, Network and API

Authentication

TaskCode
Save a loginawait page.context().storageState({ path: 'playwright/.auth/user.json' })
Use ituse: { storageState: 'playwright/.auth/user.json' }
Logged outtest.use({ storageState: { cookies: [], origins: [] } })

Network

TaskCode
Mock JSONawait page.route('**/api/products*', r => r.fulfill({ json: [] }))
Fail a callroute.fulfill({ status: 500 }) or route.abort()
Change a callroute.continue({ headers: { ... } })
Edit real dataconst res = await route.fetch(); route.fulfill({ response: res, json })
Wait for a callconst res = page.waitForResponse('**/api/x'); await click; await res
Offlineawait context.setOffline(true)

API

TaskCode
GETconst res = await request.get('/api/products/2')
POST JSONawait request.post('/api/orders', { data: { productId: 1 } })
Checkawait expect(res).toBeOK(), res.status(), await res.json()
Token for all callstest.use({ extraHTTPHeaders: { Authorization: 'Bearer ...' } })
Shares page cookiespage.request.post(...)

Simple lesson: storage state for logins, page.route for mocks, request for the API.

Debugging, Reporting and CI

NeedUse
Why did it fail?Error, call log, code frame, then the trace
Step through--debug, await page.pause(), VS Code breakpoints
All-in-onenpx playwright test --ui
Record what happenedtrace: 'on-first-retry', then show-trace
Page messagespage.on('console', m => ...), page.on('pageerror', e => ...)
Reportslist or dot in the terminal, html for people, junit and json for tools
CInpm ci, npx playwright install --with-deps, npx playwright test, upload the report
Faster CIfullyParallel: true, --shard=x/y, blob reports and merge-reports
Time-based pagespage.clock.setFixedTime(...), install(), fastForward()
Accessibilitynew AxeBuilder({ page }).analyze(), toMatchAriaSnapshot()
AI agents@playwright/mcp, playwright-cli, npx playwright init-agents --loop=claude

Stuck on a test? Run it once with --trace on and open the trace. Most mysteries are solved by looking at the page snapshot at the failing step.

Playwright changes every month. When an option here does not work, check the release notes for your version in the Playwright docs.

Simple lesson: the trace answers most questions. Reports and CI share the answers with your team.

TL;DR

  • CLI: npx playwright test plus flags. show-report and show-trace open results.
  • Locators: roles, labels and test ids first. Filter and chain.
  • Assertions: await expect(locator)... retries. Plain expect does not.
  • Config and fixtures set up every test. Storage state logs in once.
  • page.route mocks, request calls the API, traces explain failures.
  • CI: install, test, upload. Shard for speed.

Common mistakes

MistakeWhat happensFix
CSS and XPath firstTests break when the design changesRoles, labels, test ids
Missing awaitFlaky tests and lost failuresAwait every action and web-first assertion
waitForTimeout()Slow and still flakyWeb-first assertions
Logging in through the form everywhereSlow suitesStorage state and a setup project
No traces or reports on CIFailures nobody can explainUpload playwright-report and traces

Check Yourself

Exercises

What to Remember

  • This page is a map. The named lessons are the territory.
  • Roles and labels, web-first assertions, no fixed waits.
  • Log in once, mock what is rare, test the API directly.
  • Traces, reports and CI turn failures into fixes.
  • You now know Playwright from the first test to AI agents. Keep practising on real projects.