First test
Introduction
Playwright is a browser automation library and test runner for Chromium, Firefox, and WebKit. This covers the JavaScript and TypeScript API.
- Playwright documentation (playwright.dev)
- API reference (playwright.dev)
Install
npm init -y
npm install --save-dev @playwright/test
npx playwright install chromium
Running npx playwright install downloads browser binaries; on Linux, add --with-deps for system libraries.
See: Installation
Write a test
import { test, expect } from '@playwright/test'
test('has a title', async ({ page }) => {
await page.goto('https://playwright.dev/')
await expect(page).toHaveTitle(/Playwright/)
})
Tests live in tests/ by default and each gets an isolated page.
See: First test
Run tests
npx playwright test
npx playwright test --ui
npx playwright test login.spec.ts
npx playwright test --project=chromium
npx playwright test --headed
UI mode shows a time-travel view of each step. Add --headed to watch the browser run. To record actions as test code, use npx playwright codegen.
See: Command line
Locators
By role
await page.getByRole('button', {
name: 'Sign in'
}).click()
Role locators match how users and assistive technology see the page.
See: Locators
By label
await page.getByLabel('Email')
.fill('a@b.com')
Matches a form control through its associated label.
See: Locators
By text
await expect(page.getByText('Saved', {
exact: true
})).toBeVisible()
Use text for static elements; prefer roles for interactive ones.
See: Locators
By test id
await page.getByTestId('save')
.click()
Reads data-testid by default; set testIdAttribute to change it.
See: Locators
Filter a list
const row = page.getByRole('row')
.filter({ hasText: 'Alice' })
await row.getByText('Edit').click()
Filtering narrows a locator that matches several elements.
See: Locators
Frames
await page.frameLocator('#checkout')
.getByLabel('Card number')
.fill('4242')
Frame locators pierce iframes and can be chained with other locators.
See: FrameLocator
Assertions
Visible and text
await expect(page.getByText('Saved'))
.toBeVisible()
Web-first assertions retry until the condition holds or the timeout ends.
See: Assertions
Page title and URL
await expect(page).toHaveTitle(/Docs/)
await expect(page).toHaveURL(/login/)
Both matchers apply to the page rather than one element.
See: Page assertions
Count and attributes
await expect(page.getByRole('listitem'))
.toHaveCount(3)
await expect(page.getByRole('link', {
name: 'Docs'
})).toHaveAttribute('href', '/docs')
Counts and attributes are checked against the live DOM, with retries.
See: Locator assertions
Poll a value
await expect.poll(async () => {
const res = await page.request.get(
'https://api.example.com/status'
)
return res.status()
}).toBe(200)
Poll turns a synchronous matcher into a retried check over an async value.
See: Assertions
Soft assertions
await expect.soft(page.getByText('Saved'))
.toBeVisible()
Failures mark the test failed but let later steps run.
See: Assertions
Configuration
Basic config
import { defineConfig } from '@playwright/test'
export default defineConfig({
testDir: './tests',
fullyParallel: true,
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry'
}
})
Runner options sit at the top level; browser options go under use.
See: Configuration
Projects
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] }
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] }
}
]
})
Select one with npx playwright test --project=webkit.
See: Projects
Web server
export default defineConfig({
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI
}
})
Playwright starts the server before the run and stops it afterwards.
See: Web server
Timeouts and retries
export default defineConfig({
timeout: 30_000,
retries: process.env.CI ? 2 : 0,
expect: { timeout: 5_000 }
})
The test timeout covers the test, fixtures, and hooks; expect has its own.
See: Timeouts
Fixtures
Built-in fixtures
import { test, expect } from '@playwright/test'
test('health check', async ({ page, request }) => {
await page.goto('/')
const res = await request.get('/api/health')
expect(res.status()).toBe(200)
})
The argument names the fixtures Playwright sets up for that test.
See: Fixtures
Custom fixture
import { test as base } from '@playwright/test'
import type { Page } from '@playwright/test'
export const test = base.extend<{ loggedIn: Page }>({
loggedIn: async ({ page }, use) => {
await page.goto('/login')
await page.getByLabel('Email').fill('ada@example.com')
await page.getByRole('button', { name: 'Sign in' }).click()
await use(page)
await page.getByRole('button', { name: 'Sign out' }).click()
}
})
Setup runs before use() and teardown after it, so both stay in one place.
See: Fixtures
Reuse login state
export default defineConfig({
use: {
storageState: 'playwright/.auth/user.json'
}
})
Save cookies and local storage once, then load them for every test.
See: Authentication
Network mocking
Fulfill a response
await page.route('**/api/user', route => (
route.fulfill({ json: { name: 'Ada' } })
))
The request never reaches the server; the route answers it directly.
See: Network mocking
Block requests
await page.route('**/*.{png,jpg}',
route => route.abort())
Abort by URL pattern or by request type to keep a test focused.
See: Abort requests
Modify a response
await page.route('**/title',
async route => {
const res = await route.fetch()
const body = (await res.text())
.replace('Hi', 'Hello')
await route.fulfill({
response: res,
body
})
})
Fetch the real response, edit it, then fulfill with the original headers.
See: Modify responses
Wait for a response
const responsePromise =
page.waitForResponse('**/api/save')
await page.getByRole('button', {
name: 'Save'
}).click()
const response = await responsePromise
Start the promise before the click so the response is not missed.
See: Network events
Inspect traffic
page.on('request', req =>
console.log(req.url()))
page.on('response', res =>
console.log(res.status()))
Events see every request and response, including XHR and fetch calls.
See: Network events
CI
Install browsers
npm ci
npx playwright install --with-deps
npx playwright test
CI needs browser binaries and their system dependencies before the run.
Configure for CI
export default defineConfig({
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
['line'],
['html', { open: 'never' }]
]
})
One worker gives each test the whole machine; forbidOnly blocks stray focused tests.
See: CI configuration
Shard tests
npx playwright test --shard=1/4
npx playwright test --shard=2/4
Sharding splits the suite across jobs; upload each HTML report as an artifact.
See: Sharding
0 Comments for this cheatsheet. Write yours!