Playwright 30 🎭 Cheatsheet
A dense reference for the Playwright API, config, CLI, and testing patterns. Organized from install to advanced, every section a table or a snippet.
Install & CLI
npm init playwright@latest # scaffold
npm i -D @playwright/test # add to existing project
npx playwright install # all browsers
npx playwright install chromium # one browser
npx playwright install-deps # OS deps (Linux CI)
| Command | Purpose |
|---|---|
npx playwright test | Run the suite |
npx playwright test file.spec.ts | One file |
npx playwright test -g "login" | Match by title |
npx playwright test --headed | Show the browser |
npx playwright test --debug | Open the Inspector |
npx playwright test --ui | UI mode |
npx playwright test --project=chromium | One project |
npx playwright test --shard=1/3 | Shard 1 of 3 |
npx playwright test --workers=4 | Parallel workers |
npx playwright test --repeat-each=5 | Flake hunt |
npx playwright test --last-failed | Rerun failures |
npx playwright show-report | Open HTML report |
npx playwright show-trace trace.zip | Open a trace |
npx playwright codegen example.com | Record a test |
npx playwright merge-reports ./blobs | Merge shards |
Config — playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
timeout: 30_000, // per test
expect: { timeout: 5_000 }, // per assertion
fullyParallel: true,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 2 : undefined,
reporter: [['html'], ['list']],
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
testIdAttribute: 'data-testid',
viewport: { width: 1280, height: 720 },
locale: 'en-US',
timezoneId: 'Europe/Berlin',
colorScheme: 'light',
storageState: 'playwright/.auth/user.json',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'mobile', use: { ...devices['iPhone 14'] } },
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
});
| Key | Default | Meaning |
|---|---|---|
timeout | 30 000 | Per-test timeout |
expect.timeout | 5 000 | Per-assertion poll |
retries | 0 | Max retries |
workers | CPU/2 | Parallel workers |
fullyParallel | false | At the test level |
forbidOnly | false | Fail on test.only in CI |
reporter | list | html, json, junit, blob |
webServer.command | — | Dev server to launch |
use.trace | off | on, retain-on-failure, on-first-retry |
use.screenshot | off | on, only-on-failure |
use.video | off | on, retain-on-failure, on-first-retry |
Locators
Prefer role-based — accessible, refactor-proof.
page.getByRole('button', { name: 'Save' })
page.getByRole('link', { name: 'Docs', exact: true })
page.getByRole('textbox', { name: 'Email' })
page.getByRole('checkbox', { checked: true })
page.getByRole('heading', { level: 1 })
page.getByLabel('Password')
page.getByPlaceholder('Search…')
page.getByText('Order confirmed') // substring by default
page.getByAltText('Company logo')
page.getByTitle('Close')
page.getByTestId('cart-count')
| Method | Use |
|---|---|
page.locator('.css') | CSS selector |
page.locator('text=Save') | Legacy text |
page.locator('button:has-text("Save")') | Has-text pseudo |
page.locator('#id') | ID selector |
page.getByRole(...) | Preferred |
page.getByTestId(...) | Stable test id |
Chaining & filtering
// Filter a set
page.getByRole('listitem').filter({ hasText: 'Alice' })
page.getByRole('row').filter({ has: page.getByRole('button', { name: 'Edit' }) })
// Narrow by index
page.getByRole('listitem').first()
page.getByRole('listitem').last()
page.getByRole('listitem').nth(2)
// Descend into a component
page.getByRole('dialog').getByRole('button', { name: 'Confirm' })
// Union of two locators
page.getByRole('button', { name: 'Save' })
.or(page.getByRole('button', { name: 'Update' }))
Locator inspection (no retry — use with care)
await locator.count()
await locator.allTextContents()
await locator.textContent() // one-shot; use toHaveText to retry
await locator.getAttribute('href')
await locator.isVisible()
await locator.inputValue()
await locator.boundingBox()
Actions
| Action | Retry | Notes |
|---|---|---|
locator.click() | ✅ | Waits for actionable |
locator.dblclick() | ✅ | |
locator.fill(value) | ✅ | Replaces content |
locator.clear() | ✅ | |
locator.press(key) | ✅ | 'Enter', 'Control+A' |
locator.type(value) | ✅ | Keystroke-by-keystroke |
locator.pressSequentially(value) | ✅ | Alias of type |
locator.check() / .uncheck() | ✅ | |
locator.selectOption() | ✅ | Value, label, or { index } |
locator.hover() | ✅ | |
locator.dragTo(target) | ✅ | |
locator.setInputFiles(path) | ✅ | |
locator.scrollIntoViewIfNeeded() | ✅ |
await page.getByLabel('Email').fill('a@b.c');
await page.getByRole('button', { name: 'Save' }).click();
await page.getByLabel('Country').selectOption('DE');
await page.getByLabel('Terms').check();
await page.getByLabel('Bio').fill('Hello');
await page.getByLabel('Bio').press('Control+Enter');
// force-skip actionability (last resort)
await page.getByRole('button', { name: 'Save' }).click({ force: true });
// modifier keys
await page.getByRole('link').click({ modifiers: ['Control'] });
// double-click, right-click
await page.getByRole('cell').dblclick();
await page.getByRole('cell').click({ button: 'right' });
Assertions
Web-first (auto-retrying) — the ones to use:
await expect(page.getByRole('button')).toBeVisible();
await expect(page.getByRole('button')).toBeEnabled();
await expect(page.getByRole('button')).toBeDisabled();
await expect(page.getByRole('button')).toBeChecked();
await expect(page.getByRole('heading')).toHaveText('Welcome');
await expect(page.getByRole('heading')).toContainText('Wel');
await expect(page.getByRole('listitem')).toHaveCount(3);
await expect(page.getByLabel('Email')).toHaveValue('a@b.c');
await expect(page.getByRole('link')).toHaveAttribute('href', '/docs');
await expect(page.getByTestId('card')).toHaveClass(/active/);
await expect(page.getByTestId('card')).toHaveCSS('color', 'rgb(255,0,0)');
await expect(page.locator('input')).toHaveJSProperty('checked', true);
await expect(page).toHaveURL(/\/dashboard/);
await expect(page).toHaveTitle(/Dashboard/);
await expect(page.getByTestId('img')).toHaveScreenshot('img.png');
await expect(page).toHaveScreenshot('full-page.png', { fullPage: true });
Plain (no retry — snapshot the value):
expect(1 + 1).toBe(2);
expect(await page.title()).toBe('Docs'); // ❌ race
expect(await page.locator('h1').textContent()).toContain('Wel'); // ❌ race
expect(res.ok()).toBeTruthy();
expect(await res.json()).toEqual({ id: 1 });
Poll (retry any async value):
await expect.poll(async () =>
(await page.getByTestId('count').textContent())?.trim()
).toBe('3');
await expect.poll(async () =>
(await request.get('/api/status')).status()
).toBe(200);
Auto-waiting
Before each action Playwright checks:
| Check | Meaning |
|---|---|
| attached | Element is in the DOM |
| visible | Non-empty box, not display:none |
| stable | Not animating between two frames |
| enabled | Not disabled / aria-disabled |
| receives events | Not covered by another element |
| editable | For fill/type: not readonly |
Do not sleep. Use an assertion or waitForResponse:
// ❌ slow and racy
await page.waitForTimeout(1000);
// ✅ wait for the actual condition
await expect(page.getByTestId('count')).toHaveText('3');
// ✅ wait for the response
const r = page.waitForResponse('**/api/cart');
await page.getByRole('button', { name: 'Refresh' }).click();
await r;
Navigation
await page.goto('/login');
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.reload();
await page.goBack();
await page.goForward();
await page.setViewportSize({ width: 375, height: 812 });
waitUntil | When |
|---|---|
'commit' | Response received |
'domcontentloaded' | DOM ready (default) |
'load' | Load event fired |
'networkidle' | No network for 500 ms |
Network interception
// Stub a response
await page.route('**/api/users', (route) =>
route.fulfill({
status: 200,
json: [{ id: 1, name: 'Alice' }],
headers: { 'content-type': 'application/json' },
})
);
// Stub from file
await page.route('**/api/users', (route) =>
route.fulfill({ path: 'fixtures/users.json' })
);
// Abort
await page.route('**/*.{png,jpg}', (route) => route.abort());
// Modify and continue
await page.route('**/api/**', async (route) => {
const req = route.request();
const response = await route.fetch();
const body = await response.json();
body.patched = true;
await route.fulfill({ response, json: body });
});
// Observe only
page.on('request', (r) => console.log('→', r.method(), r.url()));
page.on('response', (r) => console.log('←', r.status(), r.url()));
page.on('requestfailed', (r) => console.log('✗', r.url()));
// Wait for a specific response
await page.waitForResponse('**/api/order');
// Wait with a predicate
await page.waitForResponse((r) =>
r.url().endsWith('/api/order') && r.status() === 201
);
// waitForRequest
const req = page.waitForRequest('**/api/login');
// Remove a route
await page.unroute('**/api/users');
Authentication & storage state
// tests/auth.setup.ts — run once via a setup project
import { test as setup } from '@playwright/test';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByLabel('Password').fill('secret');
await page.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL('**/dashboard');
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
// playwright.config.ts
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
],
// Inline, per test — for a second user
test.use({ storageState: 'playwright/.auth/admin.json' });
Fixtures
// tests/fixtures.ts
import { test as base } from '@playwright/test';
type Fixtures = {
login: () => Promise<void>;
todoPage: TodoPage;
};
export const test = base.extend<Fixtures>({
login: async ({ page }, use) => {
await use(async () => {
await page.goto('/login');
await page.getByLabel('Email').fill('u@e.com');
await page.getByRole('button', { name: 'Sign in' }).click();
});
},
todoPage: async ({ page }, use) => {
const todo = new TodoPage(page);
await use(todo);
},
});
export { expect } from '@playwright/test';
// Override an option for one file
test.use({ viewport: { width: 375, height: 812 } });
// Worker-scoped fixture (shared across a file)
export const test = base.extend<{}, { db: string }>({
db: [async ({}, use) => {
const conn = await connect();
await use(conn);
await conn.close();
}, { scope: 'worker' }],
});
Hooks & structure
import { test, expect } from '@playwright/test';
test.describe('checkout', () => {
test.beforeAll(async () => { /* once per worker */ });
test.beforeEach(async ({ page }) => { await page.goto('/'); });
test.afterEach(async ({ page }, info) => {
if (info.status !== 'passed') await page.screenshot({ path: `fail-${info.title}.png` });
});
test.afterAll(async () => { /* once per worker */ });
test('adds an item', async ({ page }) => {
await page.getByRole('button', { name: 'Add' }).click();
});
test('removes an item', async ({ page }) => {
test.skip(page.viewportSize()!.width < 600, 'desktop only');
await page.getByRole('button', { name: 'Remove' }).click();
});
});
Steps & annotations
// Named steps in the report and trace
await test.step('checkout', async () => {
await page.getByRole('button', { name: 'Pay' }).click();
await expect(page.getByText('Confirmed')).toBeVisible();
});
| Annotation | Effect |
|---|---|
test.skip() | Skip |
test.skip(condition, reason) | Conditional skip |
test.fail() | Expect failure |
test.fixme() | Mark to fix (skipped) |
test.slow() | Triple the timeout |
test.only() | Only this test (fails under forbidOnly in CI) |
test.setTimeout(60_000) | Per-test timeout |
test.describe.configure({ mode: 'serial' }) | Chain tests in a file |
test.info().annotations.push({ type, description }) | Metadata |
// Soft assertions — collect all, fail at the end
await expect.soft(page.getByTestId('count')).toHaveText('3');
await expect.soft(page.getByTestId('total')).toHaveText('$9.99');
Test IDs & use scoping
// Change the testid attribute
use: { testIdAttribute: 'data-cy' }
// Per file
test.use({ testIdAttribute: 'data-qa' });
Timeouts cheat sheet
| Option | Default | Applies to |
|---|---|---|
timeout (config) | 30 000 | Test body |
expect.timeout | 5 000 | expect(locator) and expect.poll |
actionTimeout | 0 (test timeout) | click, fill, type, etc. |
navigationTimeout | 0 (test timeout) | goto, reload |
expect.soft | inherits | Same as expect.timeout |
// Per test
test.setTimeout(60_000);
// Per action (one-off)
await page.getByRole('button').click({ timeout: 10_000 });
// Per assertion
await expect(page.getByTestId('x')).toHaveText('y', { timeout: 15_000 });
// Global
expect: { timeout: 10_000 }
API request fixture
import { test, expect } from '@playwright/test';
test('list orders', async ({ request }) => {
const res = await request.get('/api/orders');
expect(res.ok()).toBeTruthy();
expect(res.status()).toBe(200);
const body = await res.json();
expect(body).toHaveLength(3);
});
// POST with body
await request.post('/api/orders', {
data: { item: 'book', qty: 2 },
headers: { authorization: `Bearer ${token}` },
});
// Form encoding
await request.post('/api/login', {
form: { email: 'a@b.c', password: 'secret' },
});
// In a page test — reuse cookies from `page`
const pageRes = await page.request.get('/api/me');
Multiple tabs & popups
// Wait for a new page (e.g. target="_blank")
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.getByRole('link', { name: 'Open' }).click(),
]);
await popup.waitForLoadState();
await expect(popup).toHaveTitle(/Dashboard/);
// Enumerate open pages
for (const p of page.context().pages()) console.log(p.url());
// Programmatic new tab
const second = await page.context().newPage();
await second.goto('/settings');
// A dialog
page.on('dialog', (d) => d.accept()); // or d.dismiss()
page.once('dialog', (d) => { expect(d.message()).toContain('Sure?'); d.accept(); });
Frames
// Frame by locator
await page.frameLocator('#checkout').getByRole('button', { name: 'Pay' }).click();
// Frame by name or URL
const frame = page.frame({ name: 'payment' });
const frame2 = page.frame({ url: /pay\.example\.com/ });
// Enumerate frames
for (const f of page.frames()) console.log(f.url());
Emulation — clock, locale, media
// Fake clock — install before goto so the app sees it from line one
await page.clock.install({ time: new Date('2025-01-01T00:00:00Z') });
await page.goto('/dashboard');
await page.clock.fastForward(30_000); // ms
await page.clock.fastForward('02:00:00'); // or a duration string
await page.clock.pauseAt(new Date('2025-01-01T12:00:00Z'));
await page.clock.resume();
await page.clock.runFor(5_000); // fire due timers, then stop
// Emulate media
await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' });
await page.setViewportSize({ width: 375, height: 812 });
// Geolocation
await page.context().setGeolocation({ latitude: 52.5, longitude: 13.4 });
await page.context().grantPermissions(['geolocation']);
// Permissions
await page.context().grantPermissions(['notifications', 'clipboard-read']);
// Offline
await page.context().setOffline(true);
Multi-origin & cross-domain (no boundary)
test('cross origin flow', async ({ page }) => {
await page.goto('https://auth.example.com/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByRole('button', { name: 'Sign in' }).click();
// no cy.origin(); a plain goto
await page.goto('https://shop.example.com/checkout');
await page.getByRole('button', { name: 'Pay' }).click();
});
Trace & screenshots
// Traces via config
use: {
trace: 'on-first-retry',
// or object form for granular control
trace: {
mode: 'retain-on-failure',
snapshots: true,
screenshots: false, // lighter archives
sources: true,
},
}
// Programmatic — no Playwright Test
await context.tracing.start({ snapshots: true, screenshots: true });
// ... run ...
await context.tracing.stop({ path: 'trace.zip' });
// Chunks — several archives in one session
await context.tracing.start({ snapshots: true });
// window 1
await context.tracing.stopChunk({ path: 'trace-a.zip' });
// window 2
await context.tracing.stopChunk({ path: 'trace-b.zip' });
// Screenshots
await page.screenshot({ path: 'home.png', fullPage: true });
await page.getByTestId('card').screenshot({ path: 'card.png' });
// Visual regression
await expect(page).toHaveScreenshot('home.png', { maxDiffPixels: 50 });
await expect(page.getByTestId('card')).toHaveScreenshot('card.png');
npx playwright show-trace trace.zip
npx playwright show-trace --host 0.0.0.0 --port 9323 trace.zip # network
# drag onto trace.playwright.dev — local, no upload
Debugging
| Tool | Use |
|---|---|
--debug | Inspector, PWDEBUG=1 equivalent |
--headed | Watch the browser |
--ui | UI mode with time travel |
DEBUG=pw:api=1 | Verbose API logs |
page.pause() | Break here |
| Trace viewer | Post-hoc inspection |
page.on('console') | Log client console |
page.on('pageerror', e => …) | Uncaught errors |
page.on('console', (m) => console.log(`[${m.type()}]`, m.text()));
page.on('pageerror', (err) => console.error('PAGE ERROR', err.message));
await page.pause(); // with --debug
Reporters
reporter: [
['list'],
['html', { outputFolder: 'playwright-report', open: 'never' }],
['json', { outputFile: 'results.json' }],
['junit', { outputFile: 'junit.xml' }],
['blob'], // for merge-reports
]
| Reporter | Purpose |
|---|---|
list | Console, per-test |
line | Console, compact |
dot | Minimal |
html | Interactive report |
json | Machine-readable |
junit | CI systems |
github | GitHub Actions annotations |
blob | Merge shards |
Parallelism & sharding
// Parallel at the test level
fullyParallel: true
// Serial — chain in one file
test.describe.configure({ mode: 'serial' });
// Per-file dependency ordering
test.describe.configure({ mode: 'default' });
# Shard across machines
npx playwright test --shard=1/4 --reporter=blob
npx playwright test --shard=2/4 --reporter=blob
npx playwright test --shard=3/4 --reporter=blob
npx playwright test --shard=4/4 --reporter=blob
# Merge into one report
npx playwright merge-reports --reporter html ./all-blob-reports
Component testing (experimental)
npm init playwright@latest -- --ct
npm i -D @playwright/experimental-ct-react
// playwright/index.html
// <div id="root"></div>
// <script type="module" src="./index.ts"></script>
// src/Button.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import Button from './Button';
test('fires onClick', async ({ mount }) => {
let n = 0;
const c = await mount(<Button label="Save" onClick={() => n++} />);
await c.click();
expect(n).toBe(1);
});
test('updates', async ({ mount }) => {
const c = await mount(<Counter count={0} />);
await c.update(<Counter count={5} />);
await expect(c).toHaveText('5');
});
| Key | Purpose |
|---|---|
ctPort | Vite dev server port (3100) |
ctViteConfig | Aliases, plugins |
ctTemplateDir | Folder with index.html + index.ts |
beforeMount / afterMount | Hooks in playwright/index.ts |
mount() / component.update() | Render / re-render |
Performance — Core Web Vitals
// Observer installed before navigation; buffered replays past entries
await page.addInitScript(() => {
window.__vitals = { LCP: 0, CLS: 0, INP: 0, FCP: 0 };
new PerformanceObserver((l) => {
const e = l.getEntries();
window.__vitals.LCP = e[e.length - 1].startTime; // newest, not largest
}).observe({ type: 'largest-contentful-paint', buffered: true });
new PerformanceObserver((l) => {
for (const e of l.getEntries())
if (!e.hadRecentInput) window.__vitals.CLS += e.value;
}).observe({ type: 'layout-shift', buffered: true });
new PerformanceObserver((l) => {
for (const e of l.getEntries())
if (e.duration > window.__vitals.INP) window.__vitals.INP = e.duration;
}).observe({ type: 'event', buffered: true, durationThreshold: 16 });
new PerformanceObserver((l) => {
for (const e of l.getEntries())
if (e.name === 'first-contentful-paint') window.__vitals.FCP = e.startTime;
}).observe({ type: 'paint', buffered: true });
});
// CDP metrics (Chromium only)
const client = await context.newCDPSession(page);
await client.send('Performance.enable');
const { metrics } = await client.send('Performance.getMetrics');
// cumulative — subtract before/after for a window
// Throttle
await client.send('Network.emulateNetworkConditions', {
offline: false, latency: 150,
downloadThroughput: (1.6 * 1024 * 1024) / 8,
uploadThroughput: (750 * 1024) / 8,
});
await client.send('Emulation.setCPUThrottlingRate', { rate: 4 });
| Metric | Good | Poor |
|---|---|---|
| LCP | ≤ 2.5 s | > 4.0 s |
| INP | ≤ 200 ms | > 500 ms |
| CLS | ≤ 0.1 | > 0.25 |
| FCP | ≤ 1.8 s | > 3.0 s |
| TTFB | ≤ 800 ms | > 1800 ms |
Cypress → Playwright migration
| Cypress | Playwright |
|---|---|
cy.visit(url) | page.goto(url) |
cy.get('[data-cy=x]') | page.getByTestId('x') |
cy.contains('Save') | page.getByText('Save') |
cy.get('button').contains('Save') | page.getByRole('button', { name: 'Save' }) |
.eq(n) | .nth(n) |
.find('.x') | .locator('.x') |
.within($el) | assign parent + chain |
cy.intercept('GET', url, stub) | page.route(url, r => r.fulfill(...)) |
cy.wait('@alias') | page.waitForResponse(url) |
cy.fixture('u.json') | import u from './u.json' |
cy.task('x') | ordinary Node function |
cy.request() | request.get() |
cy.session() | storageState + setup project |
Cypress.Commands.add() | test.extend({ ... }) |
cy.clock() | page.clock.install() |
cy.get('iframe').its('0.contentDocument') | page.frameLocator(...) |
cy.origin() | no boundary — plain goto |
cy.wait(1000) | ❌ — use expect / waitForResponse |
The retry model shift:
| Concept | Cypress | Playwright |
|---|---|---|
| Query timing | once per chain | lazy, every action |
| Retry scope | chain ending in assertion | action + expect(locator) |
| Non-retrying | — | toBe, toEqual, toBeTruthy |
| Poll anything | cy.then loop | expect.poll() |
await needed | no | always |
| Isolation | shared per file | fresh context per test |
Device & browser presets
import { devices } from '@playwright/test';
devices['Desktop Chrome']
devices['Desktop Firefox']
devices['Desktop Safari']
devices['iPhone 14']
devices['iPhone 14 Pro Max']
devices['Pixel 7']
devices['iPad Pro 11']
devices['Galaxy S9+']
Debug operators & page events
page.on('console', (m) => {})
page.on('pageerror', (e) => {})
page.on('request', (r) => {})
page.on('response', (r) => {})
page.on('requestfailed', (r) => {})
page.on('dialog', (d) => d.accept())
page.on('popup', (p) => {})
page.on('download', (d) => {})
page.on('filechooser', (f) => {})
page.on('websocket', (ws) => {})
page.on('framenavigated',(f) => {})
// Downloads
const [download] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('link', { name: 'Export' }).click(),
]);
await download.saveAs('/tmp/export.csv');
// Downloads in context (accept all)
context.on('download', async (d) => { await d.saveAs(`/tmp/${d.suggestedFilename()}`); });
Environment & sharding in CI
# CI env vars
PLAYWRIGHT_BROWSERS_PATH=0 # download browsers into node_modules
PLAYWRIGHT_JSON_OUTPUT_NAME=out.json
CI=true # disables accidental test.only
# Sharding example (GitHub Actions)
strategy:
matrix: { shard: [1,2,3,4] }
steps:
- run: npx playwright test --shard=${{ matrix.shard }}/4 --reporter=blob
- uses: actions/upload-artifact@v4
with: { name: blob-${{ matrix.shard }}, path: blob-report/ }
# Merge shards
npx playwright merge-reports --reporter html ./blob-report
Keyboard & mouse primitives
// Keyboard
await page.keyboard.press('Enter');
await page.keyboard.press('Control+A');
await page.keyboard.type('Hello'); // key-by-key
await page.keyboard.down('Shift');
await page.keyboard.up('Shift');
await page.keyboard.insertText('😀'); // no key events
// Mouse
await page.mouse.move(100, 200);
await page.mouse.down();
await page.mouse.up();
await page.mouse.click(100, 200);
await page.mouse.wheel(0, 500);
Test utilities
// Expect a value to poll into a state
await expect.poll(async () => await page.getByTestId('n').textContent())
.toBe('3');
// Serialize a serializable value into a fixture
test('…', async ({ page }, info) => {
info.annotations.push({ type: 'issue', description: 'JIRA-123' });
});
// Attach a file to the trace
await info.attach('order.json', {
body: JSON.stringify(order),
contentType: 'application/json',
});
// Capture the exact state mid-action
await page.evaluate(() => (window as any).__snapshot);
Common pitfalls
| Pitfall | Cause | Fix |
|---|---|---|
| Test “passes” but does nothing | Missing await | ESLint no-floating-promises |
| Assertion never retries | Read value, then toBe | expect(locator).toHaveX() |
| Flaky shared state | Singleton in beforeEach | Fresh context per test |
| Click not firing | Covered by an overlay | Inspect actionability in the trace |
| Trace empty | Mode is off | on-first-retry |
| Selector not found | Wrong testIdAttribute | Set in config |
| Timeout | Default 30 s | test.setTimeout() / expect.timeout |
| Stale element | Cypress-style thinking | Playwright re-resolves |
| Assertion slower than expected | networkidle is slow | Prefer explicit assertions |
| Auth fails | Session token not persisted | storageState after login |
The five rules to memorize
1. Every Playwright call returns a promise — await it.
await page.getByRole('button', { name: 'Save' }).click(); // ✅
page.getByRole('button', { name: 'Save' }).click(); // ❌ silent
2. Locators are lazy. Assertions retry. Actions retry.
const btn = page.getByRole('button', { name: 'Pay' }); // no query yet
await btn.click(); // query, wait, click
await expect(btn).toBeVisible(); // poll until visible
3. Only expect(locator) retries. expect(value) does not.
await expect(page.getByTestId('n')).toHaveText('3'); // ✅
expect(await page.getByTestId('n').textContent()).toBe('3'); // ❌
4. Wait for the condition, never for the clock.
await expect(page.getByTestId('count')).toHaveText('3'); // ✅
const r = page.waitForResponse('**/api/x'); await click(); await r; // ✅
await page.waitForTimeout(1000); // ❌
5. Each test gets a fresh browser context.
No cookie, cache, or storage leaks unless storageState carries them deliberately.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!