Playwright from zero to hero: a TypeScript tutorial
17 short chapters in TypeScript, checked against Playwright 1.64. Each one starts with the problem it solves, explains the idea in plain words, and ends with a self-check.
await page.goto('/login');await page.getByLabel('Email').fill('qa@example.com');await page.getByLabel('Password').fill('••••••••');await page.getByRole('button', { name: 'Log in' }).click();await expect(page).toHaveURL(/dashboard/);
In short
- Locators by role and label plus auto-waiting do most of the work of keeping Playwright tests stable.
- Every test gets its own BrowserContext: isolation is free, so never share state between tests.
- Start listening for popups, downloads and responses before the click that triggers them.
- Use the API for setup, mocks for edge cases, and the UI only for the behaviour under test.
- Debug with traces, not screenshots: trace: 'on-first-retry' in the config.
New to testing? Short glossary (12 terms)
- E2E test
- End-to-end test: drives the app through its UI like a user, from the first page to the final result.
- Locator
- An object that describes how to find an element. It is looked up again on every use.
- Assertion
- A check that a condition is true, such as await expect(page).toHaveURL(/dashboard/).
- Auto-waiting
- Playwright waits for an element to be ready before it acts on it, so you don't write sleeps.
- Flaky test
- A test that sometimes passes and sometimes fails on the same code.
- Headless
- Running the browser without a visible window. This is the default and is faster.
- Fixture
- Setup that Playwright prepares for a test and tears down afterwards, such as page or your own loginPage.
- Worker
- A separate process that runs tests. Several workers run tests in parallel.
- BrowserContext
- An isolated browser profile with its own cookies and storage. Each test gets its own.
- Trace
- A recording of a test run: every step with a DOM snapshot, network calls and console output.
- storageState
- A saved login (cookies and local storage) that tests load instead of logging in again.
- CI
- Continuous integration: a server that runs your tests automatically on every change.
What Playwright is, and why teams pick it
Playwright is Microsoft's open-source tool for end-to-end (E2E) testing of web apps. A test opens a real browser, does what a user does (type, click, navigate) and checks that the page responds correctly. One API drives Chromium, Firefox and WebKit, and the tool comes with its own test runner, reporter, trace viewer and code generator.
The painThree drivers, a runner, a reporter and a pile of sleep() calls before the first useful test.
The fixOne install: three engines, runner, reporter, traces.
- Cross-browserChromium (Chrome, Edge), Firefox and WebKit (Safari's engine), on Windows, macOS and Linux.
- Auto-waitingActions wait until an element is ready; assertions retry until they pass.
- IsolationEvery test gets a fresh browser context, its own cookies and storage, in milliseconds.
- Batteries includedParallel runs, retries, HTML report, traces, codegen, UI mode, API testing and network mocking.
- LanguagesTypeScript/JavaScript (primary, gets features first), Python, Java and .NET.
- Branded browsersSet channel: 'chrome' or 'msedge' in a project to run in real Google Chrome or Microsoft Edge instead of the bundled Chromium.
| Who | Why they use it |
|---|---|
| Manual QA moving to automation | Codegen and readable locators make the first tests quick to write. |
| Automation engineers | Fewer flaky waits, one API for three engines, built-in parallelism. |
| SDETs | Fixtures, projects and traces scale to large suites and CI. |
| Developers | Fast local feedback in UI mode, component and API tests in the same runner. |
In real lifeA shop team runs the same checkout test on Chromium, Firefox and WebKit before every release, from one config.
Tip. Where E2E tests fit: the test pyramid. Many fast unit and component tests at the bottom, fewer API (integration) tests in the middle, and a few E2E tests on top for the key user journeys. Playwright covers the top two layers: UI tests with page and API tests with request.
Check yourself
Which three browser engines does Playwright drive?
Chromium, Firefox and WebKit. Chrome and Edge run on Chromium; WebKit is the engine behind Safari.
Which language gets new Playwright features first?
TypeScript/JavaScript: the Node.js package is the primary target; the Python, Java and .NET bindings follow.
Architecture: how a command reaches the browser
Your test calls the Playwright API, and Playwright sends each command to the browser over one open connection. The browser sends events back on the same connection. There is no WebDriver server and no HTTP request per command: that is a large part of why Playwright is fast.
The painEvery command is a separate HTTP round trip, and the page has no way to tell you what just happened.
The fixOne persistent connection; the browser pushes events back.
5 commands = 5 separate requests, answered one at a time.
One pipe or WebSocket: commands go out, events (request, dialog, navigated) come back as they happen.
- Chromium is driven over the Chrome DevTools Protocol; Firefox and WebKit are Playwright-patched builds with their own protocols.
- Python, Java and .NET clients talk to a bundled Node.js driver over a pipe; the driver talks to the browsers.
- Because the connection is bidirectional, Playwright hears about network requests, dialogs, console messages and navigations the moment they happen.
- Playwright does not use Selenium or WebDriver: it is a separate stack end to end.
In real lifeA test clicks, waits for a toast and reads a network response, all on the same channel.
Tip. Locally there is nothing extra to start: Playwright launches the browsers itself and talks to them over a pipe. A separate browser server is only involved in remote setups: browserType.launchServer() or a cloud grid you connect to.
Check yourself
Why is Playwright usually faster than Selenium WebDriver?
It keeps one persistent, bidirectional connection to the browser instead of sending an HTTP request per command, and it hears about navigations, network traffic and dialogs the moment they happen.
Installation & project setup
You need a current LTS version of Node.js (it brings npm with it), an editor such as VS Code, and basic JavaScript or TypeScript. The official initializer asks four questions, TypeScript or JavaScript, the tests folder, whether to add a GitHub Actions workflow, and whether to install browsers, and generates a working project.
The painHours of setup (drivers, versions, config) before anything runs.
The fixnpm init playwright@latest writes a working project.
tests/Test files (*.spec.ts)playwright.config.tsHow tests run: browsers, timeouts, reporters, baseURLplaywright-report/Generated HTML reporttest-results/Screenshots, videos and traces from the last runpackage.json@playwright/test as a dev dependency, plus your scriptstsconfig.jsonTypeScript settings (optional: Playwright runs .ts files without it)
| Path | What it holds |
|---|---|
| tests/ | Test files (*.spec.ts) |
| playwright.config.ts | How tests run: browsers, timeouts, reporters, baseURL |
| playwright-report/ | Generated HTML report |
| test-results/ | Screenshots, videos and traces from the last run |
| package.json | @playwright/test as a dev dependency, plus your scripts |
| tsconfig.json | TypeScript settings (optional: Playwright runs .ts files without it) |
node -v # check Node.js is installed (LTS) npm init playwright@latest # new project: answers 4 questions, writes everything # or step by step, in an empty foldermkdir playwright-ts && cd playwright-tsnpm init -ynpm install -D @playwright/testnpx playwright install # run the example tests and open the reportnpx playwright testnpx playwright show-reportimport { defineConfig, devices } from '@playwright/test'; export default defineConfig({ testDir: './tests', // where tests live timeout: 30_000, // per test expect: { timeout: 5_000 }, // per assertion use: { baseURL: 'http://localhost:3000', // so page.goto('/login') works trace: 'on-first-retry', }, projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, { name: 'webkit', use: { ...devices['Desktop Safari'] } }, ],});In real lifeA new teammate clones the repo, installs the browsers and runs the whole suite in one sitting.
Tip. Install the official Playwright Test for VS Code extension: it runs a test from the gutter, shows the browser while you step through, and picks locators for you. Tests run headless by default; add --headed to watch the browsers, or --ui for the interactive runner.
Check yourself
What does npx playwright install do?
Downloads the browser builds Playwright is tested against (Chromium, Firefox, WebKit). Add --with-deps on CI images to install the OS libraries they need too.
Your first test, line by line
A Playwright test is an async function that receives a fresh browser tab called page, does what a user would do, then checks the result. Open, act, check: every test you write will have this shape. Click a line below to see what it does.
The painYou can copy a test, but you don't know what each line does or why it is async.
The fixRead it top to bottom: open, act, check.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Line 3Declares a test. The first argument is its name, shown in reports. The second is an async function. { page } asks Playwright for a fresh browser tab: a fixture, created before the test and closed after it.
- Every browser action takes time, so Playwright methods return a Promise. await pauses the test until the action has finished, so the next line sees the result.
- A test fails when any line throws: a locator that finds nothing in time, a failed assertion, a timeout.
| Line | What it does |
|---|---|
| 1 | Imports `test` (declares a test) and `expect` (checks a result) from Playwright. |
| 3 | Declares a test. The first argument is its name, shown in reports. The second is an async function. `{ page }` asks Playwright for a fresh browser tab: a fixture, created before the test and closed after it. |
| 4 | Opens the URL. When `baseURL` is set in the config, `/login` is added to it. |
| 5 | Finds the input by its label text and types the value. Playwright first waits until the field is visible and editable. |
| 6 | The same for the password field. |
| 7 | Finds the button by its role and visible name, then clicks it. Playwright waits until the button is enabled and nothing covers it. |
| 8 | The assertion. It passes as soon as the URL matches /dashboard/ and fails if it still doesn't after the timeout (5 seconds by default). |
| 9 | Ends the test. If no line threw an error, the test passes. |
npx playwright test # run everything, headlessnpx playwright test login.spec.ts # one filenpx playwright test -g "log in" # tests whose name matchesnpx playwright test --headed # watch the browsernpx playwright test --ui # interactive runnerIn real lifeThe same three steps are in every test you will write, from a login to a checkout.
Watch out. Forgetting await is the most common beginner bug. The test moves on before the click has finished, so it passes by luck or fails at random. If a test is flaky from the first day, check the awaits first.
Check yourself
Where does the page in ({ page }) come from?
From Playwright's test runner. It is a fixture: a fresh tab created for this test and closed when the test ends, so tests don't share state.
What happens if you forget await before page.click()?
The test continues before the click is done. The result depends on timing, so the test passes sometimes and fails sometimes.
Browser, BrowserContext & Page
A Browser is the running browser program. A BrowserContext is a clean, isolated profile inside it, like an incognito window, with its own cookies, local storage and permissions. A Page is one tab inside a context. The test runner creates a fresh context and page for every test, so you rarely create them yourself.
The painTests leak cookies and storage into each other, so the order they run in starts to matter.
The fixA fresh BrowserContext per test: isolated, and cheap.
| Browser | BrowserContext | Page | |
|---|---|---|---|
| What it is | A browser instance | An isolated session | One tab |
| Created by | chromium.launch() | browser.newContext() | context.newPage() |
| Cost | Heavy (seconds) | Cheap (milliseconds) | Cheap |
| Isolation | - | Cookies, storage, cache, permissions | Shares its context's state |
| Typical scope | One per worker | One per test / per user | One per tab |
import { chromium } from '@playwright/test'; const browser = await chromium.launch({ headless: false }); // start the browser programconst context = await browser.newContext({ viewport: { width: 1280, height: 720 } }); // clean profileconst page = await context.newPage(); // one tabawait page.goto('https://example.com');await browser.close(); // closes contexts and pages tootest('admin sees the user’s message', async ({ browser }) => { const adminContext = await browser.newContext({ storageState: 'playwright/.auth/admin.json' }); const userContext = await browser.newContext({ storageState: 'playwright/.auth/user.json' }); const admin = await adminContext.newPage(); const user = await userContext.newPage(); await user.goto('/chat'); await user.getByRole('textbox').fill('Hello admin'); await user.keyboard.press('Enter'); await admin.goto('/chat'); await expect(admin.getByText('Hello admin')).toBeVisible(); await adminContext.close(); await userContext.close();});In real lifeAn admin approves an order while a customer watches the status change: two contexts, one test.
Tip. In a @playwright/test test you just ask for { page } or { context }: the runner creates and closes them for you. Write chromium.launch() yourself only in scripts outside the runner.
Check yourself
How do you simulate two logged-in users at once?
Create two browser contexts (each with its own storageState) from the same browser: they don't share cookies or storage.
Locators: find elements the way users do
A locator tells Playwright how to find an element on the page, for example "the button named Log in". It is looked up again every time you use it, so it keeps working when the page re-renders. Prefer locators built from what the user sees (role, label, text) over CSS classes and XPath, which break when the markup changes.
The paindiv.card > div:nth-child(3) .btn-x breaks the day someone renames a class.
The fixgetByRole('button', { name: 'Pay' }) follows what the user sees.
- 1
getByRolebutton, link, heading, input: anything with a role - 2
getByLabelform fields with a <label> - 3
getByPlaceholderinputs with no label - 4
getByTextplain, non-interactive text - 5
getByTestIdwhen nothing user-facing is stable - 6
locator('css')last resort - 7
locator('xpath=…')last resort
locator('div.card > div:nth-child(3) .btn-x')foundnot found: test failsgetByRole('button', { name: 'Pay' })foundstill found| Priority | Locator | Use for |
|---|---|---|
| 1 | getByRole('button', { name: 'Log in' }) | Buttons, links, headings, inputs: anything with a role |
| 2 | getByLabel('Email') | Form fields with a <label> |
| 3 | getByPlaceholder('Search') | Inputs without a label |
| 4 | getByText('Welcome back') | Non-interactive text |
| 5 | getByAltText / getByTitle | Images, elements with a title |
| 6 | getByTestId('checkout-total') | When nothing user-facing is stable |
| 7 | locator('css') / locator('xpath=…') | Last resort |
await page.getByRole('textbox', { name: 'Email' }).fill('qa@example.com'); // by role + accessible nameawait page.getByLabel('Password').fill(process.env.PASSWORD!);await page.getByRole('checkbox', { name: 'Remember me' }).check();await page.getByRole('button', { name: 'Sign in' }).click(); // Narrow down instead of using an indexconst row = page.getByRole('row').filter({ hasText: 'Ada Lovelace' });await row.getByRole('button', { name: 'Edit' }).click();In real lifeA redesign renames every CSS class; role-based tests keep passing without an edit.
Watch out. getByText matches a case-insensitive substring and normalises whitespace: pass { exact: true } for an exact match. On lists that can reorder, filter by text or by a child rather than picking by index with .nth().
Check yourself
Why is getByRole preferred over a CSS selector?
It targets what users and assistive technology see (role + accessible name), so it survives class and markup changes and doubles as a light accessibility check.
What happens if a locator matches three elements and you call click()?
The test fails with a strict-mode violation. Make the locator more specific (filter, chain, name) rather than reaching for first().
Auto-waiting & web-first assertions
Pages load and change over time, so a test must not act too early. Before an action, Playwright waits until the element is actionable. For a click that means visible, stable (not animating), receiving events (nothing covering it) and enabled; for fill() it means visible, enabled and editable. Assertions made with expect(locator) retry until they pass or time out. Together they remove almost every sleep and explicit wait.
The painsleep(5000) makes the suite slow and still fails when the page takes 5.1 seconds.
The fixActions wait until the element is ready; assertions retry.
- Visible
- Stable (not animating)
- Receives events (not covered)
- Enabled
- click()
sleep(5000)click at 5.0 sclick() auto-waitsclick at 1.4 s| Assertion | Checks |
|---|---|
toBeVisible() / toBeHidden() | Visibility |
toHaveText() / toContainText() | Exact / partial text |
toHaveValue() | Input value |
toHaveAttribute() / toHaveClass() | Attributes and classes |
toBeEnabled() / toBeDisabled() / toBeChecked() | State |
toHaveCount() | Number of matches |
expect(page).toHaveURL() / toHaveTitle() | Page URL and title |
await page.getByRole('button', { name: 'Login' }).click();// no waits: both assertions retry until true (5 s by default)await expect(page).toHaveURL(/\/dashboard/);await expect(page.getByText('Welcome, QA')).toBeVisible();In real lifeA dashboard draws its chart after an API call; the test asserts on the chart instead of guessing a delay.
Watch out. Auto-waiting covers actions and expect(locator / page) assertions. A value you read yourself is read once: write await expect(locator).toHaveText('x'), which retries, rather than expect(await locator.textContent()).toBe('x'), which doesn't.
Check yourself
What does Playwright wait for before a click?
The element must be visible, stable (not animating), receiving events (not covered by another element) and enabled. fill() waits for visible, enabled and editable instead.
Actions & input methods
Actions are methods on a locator: click, fill, check, selectOption, hover, press, setInputFiles, dragTo. Each one auto-waits for the element to be actionable. Pick the method that matches what the user does: fill for typing a value, selectOption for a native select.
The painTyping key by key is slow, and clicking through a native <select> is fragile.
The fixfill() and selectOption() do what the user means.
| Method | Use it for |
|---|---|
fill('text') | Set an input's value instantly (clears first). The default. |
pressSequentially('text') | Type key by key: autocomplete, input masks |
clear() | Empty an input |
press('Enter') | One key or shortcut |
check() / uncheck() / setChecked() | Checkboxes and radios |
selectOption('UA') | Native <select>don't click options |
hover() / dblclick() / click({ button: 'right' }) | Pointer actions |
dragTo(target) | Drag and drop |
setInputFiles('file.pdf') | File inputs |
selectText() | Select the text inside an input |
await page.getByPlaceholder('Full name').fill('Ada Lovelace'); // type a valueawait page.getByLabel('Country').selectOption('UA'); // native <select>await page.getByLabel('City').pressSequentially('Kyi', { delay: 50 }); // key by key, for autocompleteawait page.getByRole('option', { name: 'Kyiv' }).click(); // pick a suggestionawait page.getByLabel('I accept the terms').check(); // checkboxawait page.getByLabel('CV').setInputFiles('fixtures/cv.pdf'); // file uploadawait page.locator('#card-7').dragTo(page.locator('#done')); // drag and drop // When no higher-level action exists, use the keyboard and mouse directlyawait page.keyboard.press('Control+A');await page.mouse.click(100, 200); // x, y in the viewportIn real lifeA signup form with a country select, an autocomplete city and a CV upload.
Watch out. Each action returns a Promise, so await them one by one: await field.fill('admin'); then await field.press('Tab'). Use { force: true } only when you know why an element isn't actionable, usually an overlay is covering it for real users too.
Check yourself
fill() or pressSequentially(), which should be the default?
fill(). It is faster and reliable; use pressSequentially() only when the page reacts to individual keystrokes.
Frames, tabs, dialogs, uploads & downloads
Real apps embed payment iframes, open links in new tabs, pop confirm dialogs and export files. Playwright handles each with a small pattern, and the rule for tabs, downloads and dialogs is the same: start listening before the click that triggers them.
The painA popup opened and the test never saw it: the event fired before anyone was listening.
The fixCreate the waitForEvent promise first, then click.
click()opens the popuppopup event firesnobody is listeningwaitForEvent('popup')starts too latetimeoutthe test fails after 30 s
const p = waitForEvent('popup')listener is attachedclick()opens the popuppopup event firescaught by the listenerawait pthe popup page is returned
- Multiple tabs: context.pages() lists every open page in the context; page.bringToFront() switches to one.
- Upload: locator.setInputFiles(path | path[]); pass [] to clear.
- Without a dialog handler Playwright dismisses dialogs automatically, so an unexpected confirm() won't hang the test.
const payment = page.frameLocator('iframe[title="Payment"]');await payment.getByLabel('Card number').fill('4242 4242 4242 4242');const popupPromise = page.waitForEvent('popup');await page.getByRole('link', { name: 'Terms' }).click();const popup = await popupPromise;await expect(popup).toHaveURL(/terms/);page.once('dialog', async (dialog) => { expect(dialog.message()).toContain('Delete this item?'); await dialog.accept(); // or dialog.dismiss(), or accept('text') for prompts});await page.getByRole('button', { name: 'Delete' }).click();const downloadPromise = page.waitForEvent('download');await page.getByRole('button', { name: 'Download report' }).click();const download = await downloadPromise;await download.saveAs(`downloads/${download.suggestedFilename()}`);In real lifeA checkout inside a payment iframe that opens a Terms popup and downloads a receipt.
Tip. One pattern covers popups, downloads, file choosers and responses: create the waitForEvent promise, click, then await the promise.
Check yourself
Why must waitForEvent('popup') be called before the click?
The popup event can fire before the click's promise resolves; if you start listening afterwards you can miss it and wait until the timeout.
Waiting: the right way
Actions and assertions already wait, so explicit waits are only for the few cases an assertion can't express: a URL change, a network response, or an element that must disappear.
The painwaitForLoadState('networkidle') never settles on pages that poll or send analytics.
The fixAssert on the element you need, or wait for the one response.
- Older tutorials use APIs you should replace: page.waitForNavigation() → page.waitForURL(); page.waitForSelector() → await expect(locator).toBeVisible() or locator.waitFor(); locator.type() → fill() or pressSequentially(); waitForLoadState('networkidle') → an assertion on the element you need.
- There is no Selenium-style implicit wait. Every action and web-first assertion already waits on its own; the timeouts in the config only set how long.
| Need | Use |
|---|---|
Element appears / changes | await expect(locator).toBeVisible() / toHaveText() |
| Element disappears | await expect(spinner).toBeHidden() or locator.waitFor({ state: 'hidden' }) |
| URL changes after a click | await page.waitForURL('**/next') or expect(page).toHaveURL() |
| A specific API call finished | page.waitForResponse('**/api/orders'): started before the click |
| Adjust patience | { timeout } on one assertion, or expect.timeout in config |
const saved = page.waitForResponse((r) => r.url().includes('/api/profile') && r.request().method() === 'PUT');await page.getByRole('button', { name: 'Save' }).click();expect((await saved).ok()).toBe(true);await expect(page.getByRole('status')).toHaveText('Saved');In real lifeSave a profile, wait for the PUT to finish, then read the success message.
Tip. Timeouts are limits, not waits: setDefaultTimeout() and { timeout } only change how long Playwright keeps trying before it fails. To know a page is ready, assert on the element you need: pages with polling or analytics never go network-idle.
Check yourself
How do you wait for the URL to change after a click?
Click, then await page.waitForURL(pattern), or assert with await expect(page).toHaveURL(pattern), which retries until the URL matches.
API testing & network interception
The request fixture sends HTTP calls without a browser: ideal for API tests and for fast setup. page.route() intercepts the browser's own traffic so you can mock responses, patch real ones, change requests or block resources.
The painTesting an error page means breaking a real backend, or waiting for it to break by itself.
The fixroute.fulfill() returns a 500 on demand, in one line.
You answer. The server is never called. route.fulfill({ status: 500 })
The request goes on, optionally changed. route.continue({ url })
Real response, one field patched. route.fetch() → route.fulfill({ json })
- Test error states cheaply: fulfill with status 500 and check the UI's error message.
- Use API calls to create and delete test data; keep the UI for the behaviour under test.
test('creates a user', async ({ request }) => { const response = await request.post('/api/users', { data: { name: 'Ada', job: 'QA' } }); await expect(response).toBeOK(); const user = await response.json(); expect(user).toMatchObject({ name: 'Ada' });});const list = await request.get('/api/users'); // readconst created = await request.post('/api/users', { data: { name: 'Ada' } }); // createawait request.put('/api/users/1', { data: { name: 'Ada L.' } }); // updateawait request.delete('/api/users/1'); // deleteexpect(list.status()).toBe(200);const api = await playwright.request.newContext({ baseURL: 'https://api.example.com', extraHTTPHeaders: { Authorization: `Bearer ${process.env.API_TOKEN}` },});// Mock: never hit the serverawait page.route('**/api/users', (route) => route.fulfill({ status: 200, json: { data: [{ id: 1, name: 'Mock User' }] } }),); // Patch: real response, one field changedawait page.route('**/api/flags', async (route) => { const response = await route.fetch(); const json = await response.json(); await route.fulfill({ response, json: { ...json, newCheckout: true } });}); // Modify the requestawait page.route('**/api/search**', (route) => { const url = new URL(route.request().url()); url.searchParams.set('limit', '5'); return route.continue({ url: url.toString() });});In real lifeCheck the empty state and the error banner without touching a server.
Check yourself
route.fulfill() vs route.continue() vs route.fetch()?
fulfill answers the request yourself (mock); continue sends it on, optionally modified; fetch performs it and returns the real response so you can patch and then fulfill.
Fixtures, hooks, parallelism & projects
Fixtures are Playwright's dependency injection: a test lists what it needs ({ page, loginPage, apiClient }) and gets it, with setup and teardown handled for it. Hooks still exist for simple cases. Tests run in parallel worker processes, and projects run the same tests against different browsers or settings.
The painThe same login block is pasted into forty tests, and the suite runs one test at a time.
The fixFixtures hold the setup once; workers run tests side by side.
- chromium
- firefox
- webkit
- Workers: set workers in the config or --workers=4; fullyParallel: true also parallelises tests inside one file.
- Projects: the same suite on Chromium, Firefox and WebKit, or on mobile viewports, or with a setup project that logs in first.
- Sharding: --shard=1/4 splits the suite across CI machines.
| Hook | Runs | Scope |
|---|---|---|
beforeAll / afterAll | Once per worker process (again after a worker restarts on failure) | Worker |
beforeEach / afterEach | Around every test | Test |
import { test as base } from '@playwright/test';import { LoginPage } from '../pages/login.page'; export const test = base.extend<{ loginPage: LoginPage }>({ loginPage: async ({ page }, use) => { await use(new LoginPage(page)); // code after use() is teardown },});export { expect } from '@playwright/test';test.beforeEach(async ({ page }) => { await page.goto('/');}); test.afterEach(async ({ page }, testInfo) => { if (testInfo.status !== testInfo.expectedStatus) console.log(`Failed on ${page.url()}`);});In real lifeEvery spec needs a logged-in `LoginPage`; one fixture replaces forty copies.
Watch out. beforeAll runs once per worker process: with 4 workers, 4 times, and again if a worker restarts after a failure. For one-time global work such as seeding data or logging in, use a setup project with dependencies, or globalSetup.
Check yourself
How is a fixture's teardown written?
Anything after await use(value) runs after the test finishes: close connections, delete data, and so on.
Page objects & project structure
When many tests use the same screen, the same locators get copied into every file, and one UI change breaks them all. A page object is a small class that holds one page's locators and actions. Tests call login() instead of repeating three lines, and a changed button is fixed in one place.
The painThe same locator is copied into twenty tests, and one UI change breaks all of them.
The fixOne class per page: change it once.
login.spec.tswhat should be truecheckout.spec.tswhat should be trueprofile.spec.tswhat should be trueadmin.spec.tswhat should be true
email, password, submitgoto(), login()how to do it- A page object answers how: how to log in, how to add to the cart. The test answers what should be true afterwards.
- Expose locators (readonly email) so a test can assert on them: expect(login.email).toBeVisible().
- Create page objects in fixtures so tests simply ask for loginPage and never call new LoginPage(page) themselves.
| Folder | What goes there |
|---|---|
tests/ | Spec files. They describe behaviour and contain the assertions. |
pages/ | One page object per page or big component: locators and actions. |
fixtures/ | test.extend() setup that hands page objects and helpers to tests. |
utils/ | Small helpers: random emails, date formatting, API clients. |
data/ | Test data files (JSON, CSV) kept out of the test code. |
playwright.config.ts | Browsers, timeouts, reporters, baseURL. |
import type { Page, Locator } from '@playwright/test'; export class LoginPage { readonly email: Locator; readonly password: Locator; readonly submit: Locator; constructor(private page: Page) { this.email = page.getByLabel('Email'); this.password = page.getByLabel('Password'); this.submit = page.getByRole('button', { name: 'Log in' }); } async goto() { await this.page.goto('/login'); } async login(email: string, password: string) { await this.email.fill(email); await this.password.fill(password); await this.submit.click(); }}import { test, expect } from '../fixtures/test'; // the fixture from the previous chapter test('valid user lands on the dashboard', async ({ loginPage, page }) => { await loginPage.goto(); await loginPage.login('qa@example.com', 'secret123'); await expect(page).toHaveURL(/dashboard/);});In real lifeThe login button gets a new label. You edit LoginPage once and every test passes again.
Tip. This chapter is the small version. The scalable framework guide covers per-environment config, test data and CI.
Watch out. Keep assertions out of most page-object methods and avoid deep inheritance. A BasePage with thirty methods turns into a second framework that everyone has to learn. Small classes with locators and a few actions are enough.
Check yourself
Why keep expect() out of page objects?
The page object shouldn't decide what is correct. The same login() may be used by a test that expects success and by one that expects an error message.
Reporting & debugging
Playwright's best debugging tool is the trace: a recording of every action with DOM snapshots, network, console and source you can scrub through. Pair it with the HTML report, UI mode for local work and the Inspector for stepping line by line.
The pain'Failed on CI' with a screenshot of a blank page and no idea why.
The fixA trace records the DOM, network and console at every step.
- DOM
- Still on /login, banner: “Session expired”
- Network
- Last request: POST /api/login · 401
- Error
- Expected /dashboard, received /login
| Tool | Command | Best for |
|---|---|---|
| HTML report | npx playwright show-report | What failed, with screenshots and traces attached |
| Trace viewer | npx playwright show-trace trace.zip | Why it failed: DOM, network and console at each step |
| UI mode | npx playwright test --ui | Local development: watch mode, time travel, pick locators |
| Inspector | npx playwright test --debug | Stepping through a test line by line |
| PWDEBUG | PWDEBUG=1 npx playwright test | The same Inspector via an environment variable, handy in npm scripts |
| Pause | await page.pause() | Stop at one line and explore |
| Codegen | npx playwright codegen <url> | Recording a first draft and finding locators |
use: { trace: 'on-first-retry', // or 'retain-on-failure' screenshot: 'only-on-failure', video: 'retain-on-failure',},reporter: [['html'], ['list']], // add 'junit' or 'allure-playwright' for CI dashboardstest('checkout', async ({ page }) => { await test.step('Add the item to the cart', async () => { await page.getByRole('button', { name: 'Add to cart' }).click(); }); await test.step('Pay', async () => { await page.getByRole('button', { name: 'Pay' }).click(); }); // the report and the trace show these as named steps});In real lifeA test fails one run in ten on CI; the trace of the failed attempt shows a stale response.
Check yourself
Which is more useful for a CI failure: a video or a trace?
The trace. It shows the DOM, network, console and the exact locator at every step; a video only shows pixels.
Stable tests: best practices & common mistakes
A flaky test passes and fails on the same code. Most flakiness comes from a short list of habits. Each row below pairs the habit to avoid with the one to use, and says why.
The painTests pass on your machine and fail on CI one run in ten.
The fixReplace a few habits and most flakiness goes away.
CSS classes and XPath copied from DevTools
getByRole, getByLabel, getByTestId
User-facing locators survive redesigns.
expect(await locator.textContent()).toBe('Saved')await expect(locator).toHaveText('Saved')The first retries until it passes; the second reads once.
page.waitForTimeout(3000)Wait for a condition: visible, URL, response
A fixed pause is slow when the page is fast and still fails when it is slow.
Test B needs what test A created
Each test creates its own data
Tests then run in any order and in parallel.
One 40-step test that checks everything
One behaviour per test
A failure points at one thing.
Logging in through the UI in every test
Log in once and reuse storageState
Saves seconds per test, thousands per run.
Clicking through five screens to prepare data
Create data through the API
The UI is slow; keep it for what you are testing.
.first() or .nth(2) to silence a strict-mode errorNarrow the locator with filter() or a nameIndex-based locators break when the list order changes.
- Speed: run in parallel (workers, fullyParallel), split across machines with --shard, and turn on traces only on retry.
- Treat a retry that passes as a warning, not as a fix. Open its trace and find the cause.
- Run headless on CI and headed (or --ui) while you write the test.
| Do this | Not this | Why |
|---|---|---|
| getByRole, getByLabel, getByTestId | CSS classes and XPath copied from DevTools | User-facing locators survive redesigns. |
| await expect(locator).toHaveText('Saved') | expect(await locator.textContent()).toBe('Saved') | The first retries until it passes; the second reads once. |
| Wait for a condition: visible, URL, response | page.waitForTimeout(3000) | A fixed pause is slow when the page is fast and still fails when it is slow. |
| Each test creates its own data | Test B needs what test A created | Tests then run in any order and in parallel. |
| One behaviour per test | One 40-step test that checks everything | A failure points at one thing. |
| Log in once and reuse storageState | Logging in through the UI in every test | Saves seconds per test, thousands per run. |
| Create data through the API | Clicking through five screens to prepare data | The UI is slow; keep it for what you are testing. |
| Narrow the locator with filter() or a name | .first() or .nth(2) to silence a strict-mode error | Index-based locators break when the list order changes. |
export default defineConfig({ fullyParallel: true, // tests in one file run in parallel too forbidOnly: !!process.env.CI, // fail the build if a test.only slipped in retries: process.env.CI ? 2 : 0, // retry on CI only; locally you want to see flakes workers: process.env.CI ? 4 : undefined, reporter: [['html'], ['list']], use: { trace: 'on-first-retry' }, // record a trace only when it is needed});In real lifeBefore you merge, check your test against these eight rows.
Watch out. Raising the timeout or adding retries hides a flaky test but does not fix it. The test then fails later, on a worse day, and takes longer to diagnose.
Check yourself
A test passes alone but fails in the full run. What do you suspect first?
Shared state: it depends on data or a login created by another test, or two parallel tests use the same account. Run with --workers=1 to confirm, then give each test its own data.
What's new in 2026 (Playwright 1.56 → 1.64)
The last year of releases pushed Playwright toward AI agents and toward stricter control of flaky tests. You don't need all of it on day one, but you should know it exists. 1.64 also changed a few defaults you may notice after upgrading: device descriptors now set the screen size too, --update-snapshots=missing passes the run instead of failing it, and elements inside a hidden iframe count as hidden.
The painWriting, fixing and babysitting tests by hand takes most of the week.
The fixAgents plan, generate and heal tests; locks stop overlaps.
- 1.56
- Test Agents: planner, generator, healernpx playwright init-agents sets up AI agents that plan, write and repair tests
- 1.59
- Agent-friendly CLI: --debug=cli, npx playwright traceCoding agents can debug and read traces from the terminal
- 1.62
- Playwright MCP bundled (npx playwright mcp)Connect an AI assistant to a real browser without extra packages
- retryStrategy: 'isolated'Failed tests are retried at the end of the run instead of as soon as a worker is free
- 1.63
- Test locks: { lock: 'name' }Tests sharing a lock never run at the same time
- locator.visible()Replaces the :visible CSS pseudo-class
- frameLocator() with no selectorSearch across every frame in the page
- 1.64
- locator.within()"This button, within that dialog": combine two locators you already have
- --shuffle and file-level locksRandom test order exposes hidden dependencies; test.describe.configure({ lock }) locks a whole file
- page.webmcpTest the tools a page registers for AI agents; Playwright MCP offers them to the agent by default
| Feature | Version | Why it matters |
|---|---|---|
| Test Agents: planner, generator, healer | 1.56 | npx playwright init-agents sets up AI agents that plan, write and repair tests |
| Agent-friendly CLI: --debug=cli, npx playwright trace | 1.59 | Coding agents can debug and read traces from the terminal |
| Playwright MCP bundled (npx playwright mcp) | 1.62 | Connect an AI assistant to a real browser without extra packages |
| retryStrategy: 'isolated' | 1.62 | Failed tests are retried at the end of the run instead of as soon as a worker is free |
| Test locks: { lock: 'name' } | 1.63 | Tests sharing a lock never run at the same time |
| locator.visible() | 1.63 | Replaces the :visible CSS pseudo-class |
| frameLocator() with no selector | 1.63 | Search across every frame in the page |
| locator.within() | 1.64 | "This button, within that dialog": combine two locators you already have |
| --shuffle and file-level locks | 1.64 | Random test order exposes hidden dependencies; test.describe.configure({ lock }) locks a whole file |
| page.webmcp | 1.64 | Test the tools a page registers for AI agents; Playwright MCP offers them to the agent by default |
test('changes global settings', { lock: 'user-settings' }, async ({ page }) => { await page.goto('/settings'); await page.getByLabel('Language').selectOption('uk'); await expect(page.getByRole('heading', { level: 1 })).toHaveText('Налаштування');});In real lifeTwo tests change the same global setting; a lock keeps them from running at once.
Check yourself
What do the three Playwright Test Agents do?
The planner explores the app and writes a Markdown test plan, the generator turns the plan into tests, and the healer runs failing tests and proposes fixes.
Interview questions & final review
If you can answer these without notes, you know Playwright well enough for most QA automation interviews, and for owning a real suite.
The painYou know the API but blank when someone asks you to explain it out loud.
The fixEight short answers cover most interviews.
- Write clean tests: one behaviour per test, independent data, no order dependency.
- Trust auto-waiting; delete sleeps.
- Keep page objects thin and assertions in tests.
- Next: build the framework from the scalable-framework guide and practise on the Playwright Sandbox.
| Question | Short answer |
|---|---|
| Why Playwright over Selenium? | Auto-waiting, one fast connection per browser, isolated contexts, built-in runner, traces and API testing. |
| What is a BrowserContext? | An isolated session with its own cookies, storage and permissions; one per test by default. |
| What is auto-waiting? | Actions wait for elements to be actionable; web-first assertions retry until they pass. |
| Locator priority? | getByRole → getByLabel → getByPlaceholder → getByText → getByTestId → CSS/XPath. |
| How does parallel execution work? | Tests are spread over worker processes; each worker has its own browser; projects and shards multiply it. |
| What is a fixture? | Injected, reusable setup/teardown a test declares in its signature: page, request, or your own. |
| How do you avoid logging in in every test? | A setup project saves storageState once; tests load it via use.storageState. |
| How do you debug a CI-only failure? | Enable trace on retry, download the report artifact and open the trace. |
In real lifeRead the table the evening before the interview, then close it and answer from memory.
Check yourself
A test passes locally and fails in CI 1 time in 10. What is your first step?
Open the trace from the failed attempt (trace on first retry) and compare it with a passing one: look for a race: an assertion on stale data, a missing wait for a response, or shared test data.
FAQ
How long does it take to learn Playwright?
A few days to write useful tests if you know basic JavaScript or TypeScript; two to four weeks alongside work to be comfortable with fixtures, network mocking and CI; a couple of months to design a framework for a team.
Do I need to know TypeScript to learn Playwright?
Basic JavaScript is enough to start, and TypeScript adds autocompletion that makes Playwright easier. Python, Java and .NET are also official options with the same concepts.
Is Playwright better than Selenium?
For most modern web apps, yes: built-in auto-waiting, faster execution, isolated contexts, a test runner, traces and API testing out of the box. Selenium still fits native mobile via Appium, legacy browsers and large healthy suites that don't need a rewrite.
What should I learn after these notes?
Build a small framework with page objects, fixtures and a CI pipeline, log in once with storageState, and practise on a sandbox app with real edge cases: frames, drag and drop, slow responses.