Bookmarks
ReferenceTesting (QA)FrontendVerified

Playwright

Playwright is a framework for end-to-end tests of web applications in Chromium, Firefox and WebKit. This reference covers locators, assertions, authentication, API testing, tracing and CI.

checked 7 Nov · next check 14 Nov · 66 min read

Sections
13
Reading
66 min
Current version
1.65.0
Written from
playwright.dev/docs/intro

Check status of the reference

Verified 7 Nov · next check 14 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Playwright is and how it works

Playwright is a framework for end-to-end (e2e) tests of web applications, with its own runner and assertions. It opens your site in a real browser and checks what a user would see. Tests run in Chromium, Firefox and WebKit on Windows, Linux and macOS, headless and in parallel, on a laptop or in CI.

It suits checks of user scenarios such as sign-up, forms, a shopping basket and signing out, as well as mobile device emulation and mixed runs where UI steps alternate with API requests. For logic that needs no browser (functions, calculations, file handling) an end-to-end test is overkill: use unit tests instead, see the pytest reference. Browser-based load testing is a separate topic, covered in the “Load testing” reference.

The Playwright Test runner reads the playwright.config.ts configuration, finds the tests and hands them out to workers: separate processes that run at the same time. Each worker has a browser open, and for every test it creates a new browser context with its own cookies and storage; the context holds a page. As a result, state does not leak from one test to the next: a failed test does not break its neighbours, and the order of execution does not matter.

The number of workers is set in the configuration; two are shown here.

A test is a function that the runner calls. It receives fixtures: ready-made objects that the runner creates before the test starts and cleans up afterwards. The main built-in fixtures are page, an open page, and context, its context. An assertion such as expect(page).toHaveTitle(...) waits for the condition to hold by itself; this is a web-first assertion. Actions also wait until the element is ready, which is called auto-waiting. For details, see the sections “Actions and auto-waiting” and “Assertions (expect)”.

typescripttests/example.spec.ts
import { test, expect } from '@playwright/test'; test('home page opens', async ({ page }) => {  await page.goto('https://example.com/');  await expect(page).toHaveTitle(/Example/);});

How it differs from Playwright Library

Playwright has two parts: @playwright/test, the runner with fixtures and assertions described above, and playwright, Playwright Library, an API for launching and controlling a browser from any script. The table shows the difference.

AspectPlaywright TestPlaywright Library
Launchthe npx playwright test commandyour own Node.js script
Fixturesbuilt in: page and context are created for youyou create the browser and context yourself
Isolationa new context for every test, no setupyou create and close contexts yourself
Parallelismworkers, retries and sharding are built inyou organise it yourself
ReportsHTML report, trace, UI Modeconsole output; the rest is up to you
When to useend-to-end tests of an applicationbrowser automation in a script, without tests

Choose Playwright Test for end-to-end tests: isolation, parallelism, assertions and reports are already built in. The playwright library is for driving a browser from an ordinary script without a runner: routine automation, demos and scraping data from pages.

This reference is written for Node.js and TypeScript. Official versions of Playwright also exist for Python, Java and .NET; in the Python world, end-to-end tests are written with a pytest plugin that provides the same fixtures and context isolation. Each language has its own documentation on playwright.dev.

What you need to know first

  • JavaScript and TypeScript are the language of the tests: functions, async/await, modules, types. See the JavaScript and TypeScript references.
  • HTML and CSS show what a page is made of: locators find elements by structure, role and text. See the HTML and CSS reference.
  • Node.js and npm are the environment the runner lives in: installing packages, running via npx. See the Node.js reference.

Section sources

the section is written from these pages

Cheat sheet

A cheat sheet of everyday Playwright commands and calls: running and debugging tests, locators, actions, assertions and API requests. The examples assume a project created with npm init playwright@latest; replace the names with your own. Each call is covered in detail in its own section of the reference.

Running tests

TaskCommand
Run all testsnpx playwright test
Run one filenpx playwright test tests/example.spec.ts
Run a test by titlenpx playwright test -g "add a todo item"
Open the browser windownpx playwright test --headed
One project from the configurationnpx playwright test --project=chromium
Without parallel executionnpx playwright test --workers=1
Rerun failed testsnpx playwright test --last-failed
List tests without running themnpx playwright test --list

By default, tests run headless and in parallel across all projects from playwright.config.ts. The --project flag keeps a single project, --workers=1 turns off parallelism, and a filter argument selects files by path.

Debugging

TaskCommand
Interactive UI Modenpx playwright test --ui
Step through in the inspectornpx playwright test --debug
Open the HTML reportnpx playwright show-report
Open a tracenpx playwright show-trace trace.zip
Record a test from your actions on a sitenpx playwright codegen demo.playwright.dev/todomvc

--ui mode shows every step of a test and the state of the page before and after it, and lets you pick a locator with the “Pick Locator” button. The --debug inspector goes through API calls line by line. For more, see the section “Debugging and tracing”.

Locators

TaskHow to write it
Find by role and namepage.getByRole('button', { name: 'Sign in' })
Form field by its labelpage.getByLabel('User Name')
Element by test idpage.getByTestId('submit-button')
Text on the pagepage.getByText('Welcome')
Narrow the set by textgetByRole('listitem').filter({ hasText: 'Product 2' })
Take the first matchgetByRole('listitem').first()

A locator finds elements again on every action and waits for them to appear. Strictness stops an action if the locator matches more than one element: narrow the set with filter or by chaining calls. Roles and labels are closest to how a person sees the page, so they are preferable to CSS selectors. For more, see the section “Locators”.

Actions

TaskHow to write it
Open a URLawait page.goto('https://example.com')
Type text into a fieldawait page.getByLabel('Email').fill('a@example.com')
Clickawait page.getByRole('button').click()
Tick a checkboxawait page.getByLabel('Subscribe').check()
Choose an option in a listawait page.getByLabel('Color').selectOption('blue')
Choose by the option’s labelawait page.getByLabel('Color').selectOption({ label: 'Blue' })
Press a keyawait page.getByRole('textbox').press('Enter')

Before every action, Playwright waits until the element is ready; this is auto-waiting, and what exactly is checked depends on the action. Tests need no fixed-time delays. For more, see the section “Actions and auto-waiting”.

Assertions

TaskHow to write it
Element is visibleawait expect(page.getByRole('dialog')).toBeVisible()
Element text matchesawait expect(heading).toHaveText('Todo')
Element contains textawait expect(row).toContainText('done')
Page URLawait expect(page).toHaveURL(/\/login/)
Page titleawait expect(page).toHaveTitle(/Playwright/)
Number of items in a listawait expect(items).toHaveCount(3)
Field valueawait expect(input).toHaveValue('a@example.com')

Assertions go through expect and retry on their own: the locator is queried again until the condition holds or the timeout expires. For more, see the section “Assertions (expect)”.

API requests

javascripttest file
import { test, expect } from '@playwright/test'; test('creates an issue', async ({ request }) => {  const response = await request.post('/repos/owner/repo/issues', {    data: { title: 'Bug report', body: 'Steps to repeat' },  });  expect(response.ok()).toBeTruthy();   const list = await request.get('/repos/owner/repo/issues');  expect(list.ok()).toBeTruthy();});

The request fixture does not open a browser: it sends HTTP requests to the baseURL from the configuration. The page.request and context.request variants take cookies from the browser context and update it when responses arrive. For more, see the section “API requests and network interception”.

Watch out

Section sources

the section is written from these pages

Installation and first run

Create a Playwright project with npm init playwright@latest: it adds the @playwright/test package, a configuration and an example test, then downloads the Chromium, Firefox and WebKit browsers. Check the installation by running the example with npx playwright test.

System requirements

You need Node.js: the latest releases of the 22.x, 24.x or 26.x lines. Supported operating systems:

SystemWhat is supported
WindowsWindows 11 or later, Windows Server 2019 or later, or Windows Subsystem for Linux (WSL)
macOSmacOS 14 (Sonoma) or later
LinuxDebian 12 or 13, Ubuntu 22.04, 24.04 or 26.04 (x86-64 or arm64)

Linux: system dependencies

On Linux, browsers need system packages: libraries without which a browser will not start. The install command installs them with the --with-deps flag, which downloads the browsers and the system dependencies in one step. To install a single browser instead of all three, add its name: npx playwright install --with-deps chromium.

bashin the project directory
npm init playwright@latest# browsers and system packages in one stepnpx playwright install --with-deps

When you create a project, the initialiser asks:

  • TypeScript or JavaScript; TypeScript by default
  • The tests directory; tests by default, or e2e if tests is taken
  • A GitHub Actions workflow, useful for running in CI
  • Whether to download browsers; yes by default

macOS and Windows

On macOS and Windows the commands are the same as on Linux, minus the last step: system dependencies are installed only on Linux. An alternative is the Playwright extension for VS Code: the “Test: Install Playwright” command in the command palette installs the package and the browsers you choose.

Checking the installation

bashin the project directory
npx playwright test

By default, tests run in parallel and headless in all the browsers set in the configuration; for a new project these are Chromium, Firefox and WebKit. Results appear in the terminal.

Useful flags for the first run:

  • --headed opens the browser window
  • --project=chromium runs one browser instead of three
  • npx playwright test tests/example.spec.ts runs a single file
  • --ui starts UI Mode, a step-by-step view of tests in the browser
bash
npx playwright show-report

After a run, the HTML reporter shows a report with filters by browser and status: passed, failed, skipped and flaky tests. If tests fail, the report opens automatically; otherwise, open it with npx playwright show-report.

Your first project

A new project looks like this:

textcontents of a new project
playwright.config.tspackage.jsonpackage-lock.jsontests/  example.spec.ts

playwright.config.ts is the central place for settings: which browsers to test, timeouts, retries, projects and reporters; see the section “Configuration and projects”. tests/example.spec.ts holds a minimal example test. npm init playwright@latest also works in an existing project: it adds the dependencies to the current package.json and leaves your tests alone.

Updating Playwright and browsers

Update the package regularly: a recent version of Playwright tests your application against the latest browser versions. Update the package and the browsers together:

bashin the project directory
npm install -D @playwright/test@latestnpx playwright install

On Linux, add the --with-deps flag so that the system packages are updated too. npx playwright --version shows the installed version; for what is new in each release line, see the section “Versions and what’s new”.

Section sources

the section is written from these pages

Locators

A locator is a way to find an element on a page at the moment of an action. A reliable locator relies on what the user sees (role and name, a field’s label, text) and points to exactly one element, so the test does not break when the markup changes.

How a locator finds an element

A locator is not a reference to a particular DOM node but a query that Playwright runs afresh every time you use it: if the markup is redrawn between two actions, the second action lands on the new node that the same query finds. An action starts with a search: before a click or typing, Playwright waits until the element appears, becomes visible and is enabled (auto-waiting). For details, see the section “Actions and auto-waiting”.

A locator is strict: if more than one element matches the query, the action fails with a “strict mode violation” error. Strictness catches vague locators at run time: narrow the query with a filter or a chain instead of taking “whichever comes first”.

typescriptsigning in with getByLabel and getByRole
import { test, expect } from '@playwright/test'; test('sign in', async ({ page }) => {  await page.goto('https://example.com');  // the field’s label is the source of the locator  await page.getByLabel('Email').fill('user@example.com');  await page.getByLabel('Password').fill('change-me');  // role and name are what the user sees  await page.getByRole('button', { name: 'Sign in' }).click();  await expect(page.getByText('Hello')).toBeVisible();});

The main method: getByRole

The getByRole method finds an element by its role and accessible name, which is how users and screen readers see the page. Roles and names are defined by the ARIA standard, so getByRole does not depend on tags or classes. Assertions with expect for locators are covered in the section “Assertions (expect)”.

typescriptgetByRole: role plus accessible name
// tags have roles by themselves: button, checkbox, headingawait page.getByRole('checkbox', { name: 'Subscribe' }).check();await page.getByRole('button', { name: /sign in/i }).click();await expect(  page.getByRole('heading', { name: 'My account' })).toBeVisible();

Built-in locator methods

Start with getByRole and use the other methods as the situation requires. Interactive elements usually have an accessible name: a label for a field, the text on a button. If there is no name, it is worth adding one, which helps both locators and the accessibility of the interface.

MethodWhen to use it
getByRolethe main method: an element with a role and a name
getByLabela form field, by the text of its label
getByPlaceholdera field with no label that has a placeholder
getByTexta non-interactive element, by text: a paragraph, div, span
getByAltTextan image, by its text alternative
getByTitlean element with a title attribute
getByTestIdan agreed attribute, when role and text do not work

The test id attribute

A test id is an attribute that the team adds to the markup specifically for tests: <button data-testid="directions">Directions</button>. getByTestId looks for it, by default using the data-testid attribute:

typescript
await page.getByTestId('directions').click();

You can change the default attribute in playwright.config.ts with the testIdAttribute key, which is useful if the project already uses its own attribute, such as data-pw:

typescriptplaywright.config.ts
import { defineConfig } from '@playwright/test'; export default defineConfig({  use: { testIdAttribute: 'data-pw' },});

A test id is the most stable anchor: it does not change when text or roles are edited. But it is not visible to the user, so where the name or role matters, go back to getByRole.

Filters and chaining

The filter method narrows a locator: hasText keeps elements with matching text (a regular expression works too), and has keeps elements that contain an element found by another locator. Methods that create locators can be chained: first limit the area (a card, a dialog, a table row), then search inside it.

typescripthasText and has filters
const product = page  .getByRole('listitem')  .filter({ hasText: 'Product 2' });await product.getByRole('button', { name: 'Add to basket' }).click();// ...and a check that there is exactly one such itemawait expect(product).toHaveCount(1);// has: a list item that contains a headingawait page  .getByRole('listitem')  .filter({ has: page.getByRole('heading', { name: 'Product 2' }) })  .getByRole('button', { name: 'Add to basket' })  .click();
typescripta button only inside a dialog
const save = page.getByRole('button', { name: 'Save' });const dialog = page.getByTestId('settings-dialog');await save.within(dialog).click();

CSS and XPath

CSS and XPath selectors are available through page.locator: strings with the css= and xpath= prefixes (strings starting with // or .. are also treated as XPath). The documentation does not recommend them: the DOM structure changes often, and tests tied to it break when the markup is edited; XPath also cannot pierce shadow DOM. Keep selectors for exceptions, such as a third-party widget with no roles or text, debugging, or a parent element via xpath=..; and if you regularly cannot do without a selector, agree on a test id.

typescriptcomparison: CSS class versus role
// brittle: breaks when a designer changes the classesawait page.locator('button.buttonIcon.episode-actions-later').click();// stable: what the user seesawait page.getByRole('button', { name: 'submit' }).click();

Frames and shadow DOM

An element inside an iframe is found through frameLocator: it takes the frame’s selector, and locators are built from there as usual. Ordinary locators do not look inside a frame.

typescripta button inside an iframe
await page  .frameLocator('#my-frame')  .getByRole('button', { name: 'Sign in' })  .click();

By default, locators pierce open shadow DOM and find elements there as if it were not there. The exceptions: XPath does not pierce a shadow root, and closed-mode shadow roots are not supported at all.

Let the tool pick a locator for you

You do not have to assemble a locator by hand: npx playwright codegen opens a site and the inspector, and the “Pick locator” button shows the locator under the cursor, prioritising role, text and test id. The Playwright extension for VS Code does the same. For details, see the section “Debugging and tracing”.

bashon the host
npx playwright codegen https://example.com

Section sources

the section is written from these pages

Actions and auto-waiting

An action in Playwright is a call to a locator method such as click, fill or check. Before each action Playwright waits for the element to be ready by itself. This is auto-waiting ([[auto-waiting]]), so tests need no explicit pauses. If the actionability checks do not pass in time, the action fails with TimeoutError.

How auto-waiting works

Every action starts with the locator pointing at exactly one element; otherwise strictness applies (see the “Locators” section). Playwright then runs the actionability checks ([[actionability checks]]) and only then acts. Until the checks pass, the action waits; if they do not pass in time, it fails with TimeoutError.

ActionWhat is checked before it runs
click, dblclick, check, uncheckvisible, stable, receives events, enabled, not inert
hover, dragTovisible, stable, receives events
fill, clearvisible, enabled, editable, not inert
selectOptionvisible, enabled, not inert
press, pressSequentiallyno state checks: focus and a key press
setInputFilesno state checks

Each check has an exact condition:

  • “attached”: the element is in the document; if it disappears from the DOM during the action, the action fails;
  • “visible”: the element has a non-empty bounding box and is not visibility:hidden; an element with opacity: 0 counts as visible;
  • “stable”: the bounding box is the same for two consecutive frames, so any animation has finished;
  • “receives events”: at the action point the topmost element is the target, so no other element covers it;
  • “enabled”: there is no disabled on the form control, on its fieldset or on an ancestor with aria-disabled;
  • “editable”: enabled and without the readonly attribute.

An inert ([[inert]]) element and its descendants are excluded from interaction: the browser does not deliver events to them, so a click on such a button has no effect. Since 1.65, fill, clear, selectOption, check and click wait for the element to stop being inert and time out if it stays inert. Another remedy for flaky checks is the auto-retrying expect assertions (see the “Assertions (expect)” section): they wait for a condition just as actions wait for readiness.

Auto-waiting checks the state of the element, not whether the page is alive. If the skeleton has rendered but JavaScript has not yet attached its handlers, Playwright can click an enabled button and the click goes nowhere. This is a hydration problem, and it is solved in the application: keep interactive elements disabled until the page is ready.

Typing text and pressing keys

The main way to enter text is fill: it waits for the checks, focuses the field and sets the whole value. It works with input, textarea and contenteditable elements. Use character-by-character typing with pressSequentially only when the page handles the keyboard itself; it sends real keydown, keyup and keypress events.

typescriptin a Playwright test
await page.getByLabel('Email').fill('user@example.com');await page.getByLabel('Password').fill('change-me'); // type character by character when the field handles keys itselfawait page.getByLabel('Code').pressSequentially('4207', {  delay: 100,});
typescriptkeys and form submission
// a single key and a key combinationawait page.getByLabel('Search').press('Control+A');await page.getByLabel('Search').press('Backspace'); await page.getByRole('button', { name: 'Sign in' }).click();await page.waitForURL('**/dashboard');

Clicks, hovering and dragging

click clicks with the primary mouse button; its options select the right button, modifiers and the click point, and dblclick performs a double click. Playwright scrolls the element into view before the action. hover moves the pointer over an element, and dragTo drags an element: hover, button press, move and release.

typescriptin a Playwright test
// right mouse buttonawait page.getByText('File').click({ button: 'right' }); // modifier: on macOS, Meta is sent instead of Ctrlawait page.getByText('File').click({  modifiers: ['ControlOrMeta'],}); await page.getByText('File').dblclick();await page.getByRole('button', { name: 'Menu' }).hover(); // drag a card to the archiveconst archive = page.locator('#archive');await page.locator('#card-42').dragTo(archive);

Checkboxes, selects and files

check and uncheck toggle checkboxes and radio buttons, and setChecked sets the state directly. In a <select> list, selectOption picks a value by its value or by the option label, and an array selects several at once. setInputFiles sets files on an input type=file field; an empty array clears the selection.

typescriptin a Playwright test
await page.getByLabel('I agree to the terms').check();await page.getByLabel('XL').check();await page.getByLabel('Subscription').uncheck(); // by value and by option labelawait page.getByLabel('Colour').selectOption('blue');await page.getByLabel('Colour').selectOption({  label: 'Blue',});await page.getByLabel('Colours').selectOption([  'red', 'green',]); await page.getByLabel('Report').setInputFiles('report.pdf');
typescripta dynamic upload field
// the file field appears on click, so start waiting firstconst chooserPromise = page.waitForEvent('filechooser');await page.getByRole('button', { name: 'Upload' })  .click();const chooser = await chooserPromise;await chooser.setFiles('report.pdf');

Navigation: goto and waitForURL

goto loads a URL and waits for the load event, when the page and its resources have loaded. But modern pages keep fetching data and rendering the interface after load, so there is no such thing as a “fully loaded” page: a click waits for its element anyway. If a click triggers a navigation, wait for the specific URL with waitForURL, because there may be several navigations.

typescriptin a Playwright test
await page.goto('https://example.com/dashboard'); await page.getByRole('link', { name: 'Profile' }).click();await page.waitForURL('**/profile');

Dialogs and file downloads

By default Playwright dismisses alert, confirm and prompt dialogs itself, as if you had pressed “Cancel”. To accept a dialog, register a page.on('dialog') handler before the action that triggers it.

typescriptin a Playwright test
page.on('dialog', dialog => dialog.accept()); await page.getByRole('button', { name: 'Delete' }).click();

A download is tied to an action, a link or a button, so start waiting for the download event before the click. The file first lands in a temporary folder and is deleted when the browser context closes, so save the file you need with saveAs.

typescriptsaving a downloaded file
// start waiting before the click, without awaitconst downloadPromise = page.waitForEvent('download');await page.getByRole('link', { name: 'Download' }).click();const download = await downloadPromise;await download.saveAs(  'downloads/' + download.suggestedFilename(),);

Forced actions

Clicks and other actions have a force: true option that skips the non-essential actionability checks. It is useful when the application itself covers a button on hover and you are sure that is by design, not a bug. In other cases force hides a problem: the click misses the target element while the test stays green. Instead, wait until the overlay disappears and click without force.

If an action fails with TimeoutError, the “Common errors and diagnostics” section explains how to find the cause from a trace.

Section sources

the section is written from these pages

Assertions (expect)

An assertion is an expect call with a matcher that compares the actual state with the expected one. Assertions on elements and pages retry on their own until the timeout, so a test does not fail while the interface is still rendering. Assertions on plain values do not wait for anything.

Web-first assertions take a locator or page: they are asynchronous, are called with await, and retry until the condition is met. Generic assertions such as toBe, toEqual and toContain check plain values and do not retry. A page shows data asynchronously, so a generic assertion against a live interface makes a test flaky; prefer retrying assertions, and describe complex conditions with expect.poll and toPass.

typescriptin a Playwright test
import { test, expect } from '@playwright/test'; test('add to cart', async ({ page }) => {  await page.goto('https://example.com/catalog');  await page.getByRole('button', { name: 'Buy' }).click();   // retries for up to 5 seconds while the page finishes rendering  await expect(page.getByText('Item added')).toBeVisible();  await expect(page.locator('.cart-item')).toHaveCount(2);  await expect(page).toHaveURL(/cart/);   // the value is already available, so a generic assertion without retries  const total = await page.locator('.total').innerText();  expect(Number(total)).toBeGreaterThan(0);});

Retries and timeouts

A retrying assertion fetches the element by its locator and checks the condition again and again until it holds or the timeout expires. By default an assertion gets 5 seconds. Set a global timeout in the config with timeout in testConfig.expect:

typescriptplaywright.config.ts
import { defineConfig } from '@playwright/test'; export default defineConfig({  expect: { timeout: 10_000 },});

To set a timeout for a single assertion, pass timeout in its options, as in toHaveText('Done', { timeout: 10_000 }). For lists, toHaveText and toContainText accept an array: the number of elements in the list must match the length of the array, and the texts must come in the same order.

AssertionRetriesChecks
expect(locator).toBeVisible()yesthe element is shown
expect(locator).toHaveText()yesthe element’s text matches in full
expect(locator).toContainText()yesthe element contains a substring
expect(locator).toHaveValue()yesthe value of an input
expect(locator).toHaveCount()yesthe exact number of elements
expect(locator).toHaveAttribute()yesthe attribute exists or equals a value
expect(page).toHaveURL()yesthe page URL
expect(page).toHaveTitle()yesthe tab title
expect(value).toBe()nothe same value
expect(value).toEqual()nodeep equality
expect(value).toContain()noa substring or an array item

Negation and soft assertions

To negate an assertion, put .not before the matcher: await expect(page.locator('.error')).not.toBeVisible(). A failed soft assertion (expect.soft) does not stop the test but marks it as failed; soft assertions work only in the Playwright test runner. You can check the accumulated soft failures at the end of a test and stop if there are any.

typescriptnegation and soft assertions
// negation: there must be no error messageawait expect(page.locator('.error')).not.toBeVisible(); // a failed soft assertion does not stop the testawait expect.soft(page.getByTestId('status'))  .toHaveText('Success');await expect.soft(page.getByTestId('eta'))  .toHaveText('1 day'); await page.getByRole('link', { name: 'Next' }).click(); // check the accumulated soft failures yourselfexpect(test.info().errors).toHaveLength(0);

Custom messages and expect.configure

The second argument of expect is a custom message for the assertion: await expect(page.getByText('Name'), 'user is signed in').toBeVisible(). It appears in the report on both failure and success. The expect.configure method builds your own expect instance with different defaults, such as a timeout or softness:

typescriptcustom expect settings
// a custom expect with a 10-second timeoutconst slowExpect = expect.configure({ timeout: 10_000 });await slowExpect(page.getByTestId('status'))  .toHaveText('Done'); // a custom expect that is always softconst softExpect = expect.configure({ soft: true });

Arbitrary conditions: poll and toPass

expect.poll turns a generic assertion into a polling one: the function is called again and again until its result passes the matcher. It suits anything that is not a page element, such as application state, an API response or a value from storage. By default polling gets 5 seconds, with growing pauses between attempts of 100, 250, 500 and 1000 ms; the timeout and intervals options change both. The method also accepts a custom message in the message option.

typescriptwaiting for an API state
// the function is polled until it returns 200await expect.poll(async () => {  const response = await page.request.get(    'https://api.example.com/status',  );  return response.status();}, { timeout: 10_000 }).toBe(200);

expect(function).toPass() retries a whole block of code until it runs without errors, for example a request followed by an assertion.

typescripta block with retries
// the block is retried until it passes as a wholeawait expect(async () => {  const response = await page.request.get(    'https://api.example.com/status',  );  expect(response.status()).toBe(200);}).toPass({ timeout: 15_000 });

Accessibility tree snapshots and screenshots

expect(locator).toMatchAriaSnapshot() compares the page’s accessibility tree with a YAML template. The template is a constraint, not a full copy: it is enough to describe the part of the structure you care about. The code generator creates snapshots, and the --update-snapshots flag updates them. expect(page).toHaveScreenshot() waits for two identical frames in a row and compares them with a reference image; the maxDiffPixels and maxDiffPixelRatio options set tolerances for differences. It also works only in the test runner.

The locators that assertions are built from are described in the “Locators” section; for how to investigate a failure from a trace, see “Debugging and tracing”.

Section sources

the section is written from these pages

Authentication and storage state

Storage state is a file with cookies and localStorage data that lets you sign in once and run all tests already authenticated. The sign-in runs in a separate setup project, and the resulting file is wired in through the configuration.

A browser context is isolated: each test gets its own cookies and storage, as described in the “What Playwright is and how it works” section. The storageState({ path }) method writes the context’s state to a JSON file, and the storageState option in the configuration creates new contexts that start with that state. The file holds cookies, localStorage, tokens from IndexedDB (with the indexedDB: true option) and passkey (WebAuthn) sign-in.

bashin the project root
mkdir -p playwright/.authecho $'\nplaywright/.auth' >> .gitignore

Move the sign-in into a tests/auth.setup.ts file. The configuration gets a setup project that finds such files through testMatch. The working projects list it in dependencies: the setup project runs to completion first, and then the other projects start. If the sign-in fails, the dependent projects do not run.

typescripttests/auth.setup.ts
import { test as setup } from '@playwright/test'; const authFile = 'playwright/.auth/user.json'; setup('sign in', async ({ page }) => {  await page.goto('https://example.com/login');  await page.getByLabel('Username').fill('user');  await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);  await page.getByRole('button', { name: 'Sign in' }).click();  // sign-in may go through redirects: wait for the final URL  await page.waitForURL('https://example.com/');  await page.context().storageState({ path: authFile });});
typescriptplaywright.config.ts
import { defineConfig, devices } from '@playwright/test'; export default defineConfig({  projects: [    { name: 'setup', testMatch: /.*\.setup\.ts/ },    {      name: 'chromium',      use: {        ...devices['Desktop Chrome'],        // every test in the project starts signed in        storageState: 'playwright/.auth/user.json',      },      dependencies: ['setup'],    },  ],});
SituationApproach
Tests do not change data on the servera shared account: sign in once in the setup project
Tests change state on the serverone account per worker, one state file per worker
Signing in through the API is simpler than the formthe request fixture in setup or in a worker fixture
Several roles in the testsone state file per role, test.use in test files
Roles meet in a single testbrowser.newContext with each role’s file

One account per worker

A worker is a runner process that runs tests in parallel with others. If tests change shared data on the server, tests that share one account interfere with each other: while one changes a setting, another checks the settings page. Create one account per worker: the sign-in runs once per worker in a worker fixture with scope: 'worker', and test.info().parallelIndex gives the worker number.

typescriptplaywright/fixtures.ts
import { test as baseTest } from '@playwright/test';import fs from 'fs';import path from 'path'; export * from '@playwright/test'; export const test = baseTest.extend<{}, { workerStorageState: string }>({  storageState: ({ workerStorageState }, use) => use(workerStorageState),  workerStorageState: [async ({ browser }, use) => {    const id = test.info().parallelIndex;    const fileName = path.resolve(      test.info().project.outputDir, `.auth/${id}.json`,    );    if (fs.existsSync(fileName)) {      await use(fileName);      return;    }    // sign in with a clean context, without anyone else’s state    const page = await browser.newPage({ storageState: undefined });    // acquireAccount returns a unique account for the given number    const account = await acquireAccount(id);    // the sign-in steps are the same as in the setup project above    await page.context().storageState({ path: fileName });    await page.close();    await use(fileName);  }, { scope: 'worker' }],});
typescripttests/example.spec.ts
// take test from the fixtures file, not from '@playwright/test'import { test, expect } from '../playwright/fixtures';

Signing in with an API request

If the application lets you sign in with an HTTP request, that is faster than filling in a form. In the setup project, use the request fixture (APIRequestContext), send a POST with the credentials and save the cookies with request.storageState({ path }). Requests are covered in the “API requests and network interception” section; the technique also works in a worker fixture.

typescripttests/auth.setup.ts
import { test as setup } from '@playwright/test'; const authFile = 'playwright/.auth/user.json'; setup('sign in through the API', async ({ request }) => {  await request.post('https://example.com/api/login', {    form: {      user: 'user',      password: process.env.TEST_PASSWORD!,    },  });  await request.storageState({ path: authFile });});

Several roles

Give each role its own state file: the setup project has several setup tests, and each saves its own file. Tests pick up a file through test.use, for a whole file or inside a test.describe; you can also set it in the use of a separate project, as in the basic recipe.

typescripttests/auth.setup.ts
import { test as setup } from '@playwright/test'; const adminFile = 'playwright/.auth/admin.json';const userFile = 'playwright/.auth/user.json'; setup('sign in as admin', async ({ page }) => {  // the admin sign-in steps are the same as in the basic recipe  await page.context().storageState({ path: adminFile });}); setup('sign in as user', async ({ page }) => {  await page.context().storageState({ path: userFile });});
typescripttests/profile.spec.ts
import { test } from '@playwright/test'; test.describe('account area', () => {  test.use({ storageState: 'playwright/.auth/user.json' });   test('profile opens', async ({ page }) => {    await page.goto('https://example.com/profile');  });});

If a single test needs two roles, create two contexts with browser.newContext calls and different state files.

typescripttests/roles.spec.ts
import { test } from '@playwright/test'; test('admin grants access to a user', async ({ browser }) => {  const admin = await browser.newContext({    storageState: 'playwright/.auth/admin.json',  });  const user = await browser.newContext({    storageState: 'playwright/.auth/user.json',  });  const adminPage = await admin.newPage();  const userPage = await user.newPage();  // the pages of both roles work independently  await admin.close();  await user.close();});

Tests without signing in

If some tests must run as a guest, reset the state: test.use with an empty state overrides the project’s file. Playwright does not save sessionStorage sign-ins: write and restore them manually, writing with page.evaluate and restoring with addInitScript.

typescripttests/guest.spec.ts
import { test } from '@playwright/test'; // an empty state instead of the project’s filetest.use({ storageState: { cookies: [], origins: [] } }); test('guest sees the sign-in page', async ({ page }) => {  await page.goto('https://example.com/');});

Section sources

the section is written from these pages

API requests and network interception

The request fixture sends HTTP requests straight from a test, without a browser: it checks an API and prepares data for an end-to-end test. Request interception replaces the page’s responses, so a test runs against stubs instead of a live server.

Requests without a browser

The request fixture is an APIRequestContext: it lives for the whole test, does not open a browser and keeps cookies between requests. Its methods are named after HTTP methods (get, post, put, patch, delete), and the generic fetch takes the method in its options. The body goes in data (an object is serialised to JSON) or in form (form fields), query string parameters go in params and headers in headers.

typescripttest file
import { test, expect } from '@playwright/test'; test('a task is created and appears in the list', async ({ request }) => {  const created = await request.post(    'https://example.com/api/tasks',    { data: { title: 'Buy coffee', done: false } },  );  await expect(created).toBeOK();  expect((await created.json()).id).toBeTruthy();   const list = await request.get('https://example.com/api/tasks');  await expect(list).toBeOK();  expect(await list.json()).toContainEqual(    expect.objectContaining({ title: 'Buy coffee' }),  );});

By default a request waits 30 seconds for a response. The timeout option sets a different limit, and failOnStatusCode: true turns status codes outside 2xx and 3xx into an error instead of a response.

Base URL and headers

You can write the host in every call or set it once in the configuration. baseURL sets the start of the URL, and calls then take a path: await request.get('/api/tasks'). extraHTTPHeaders adds headers to all requests; that is where an authorisation token goes, and the secret itself belongs in an environment variable. test.use sets the same options for a single test file.

typescriptplaywright.config.ts
import { defineConfig } from '@playwright/test'; export default defineConfig({  use: {    baseURL: 'https://example.com',    extraHTTPHeaders: {      // the token comes from an environment variable      Authorization: `Bearer ${process.env.API_TOKEN}`,    },  },});

Checking the response

A request returns an APIResponse: status() gives the status code, ok() is true for codes 200–299, and json() gives the parsed body. The await expect(response).toBeOK() assertion requires success but does not retry: the response has already arrived, so only its status is checked (for retrying assertions, see the “Assertions (expect)” section). Compare parts of the JSON with the toContainEqual and objectContaining matchers, as in the first example.

What you needCall
Status coderesponse.status()
Success (codes 200–299)response.ok()
Body as a JSON objectawait response.json()
Body as bytesawait response.body()
Response headersresponse.headers()

Preparing data through the API

In an end-to-end scenario, prepare the state with a request rather than interface steps: the test creates data through the API, opens the page and checks that the data is visible. After actions in the browser, the same approach checks the postcondition, that is, whether the data changed on the server.

typescripta test with a browser
test('a created task is visible in the interface', async ({ page }) => {  // page.request shares cookies with the page  await page.request.post('/api/tasks', {    data: { title: 'Buy coffee', done: false },  });   await page.goto('/tasks');  await expect(page.getByText('Buy coffee')).toBeVisible();});

page.request and context.request share cookies with the page, so to the server these requests look the same as browser requests. The standalone request fixture keeps its own set of cookies. To sign in with a request and pass the state on to tests, use storage state; the recipe is in the “Authentication and storage state” section.

Intercepting and mocking responses

Interception puts a handler between the page and the browser’s network stack: page.route(pattern, handler) is called for every matching request. The handler decides the request’s fate: route.continue() lets it through (optionally modified), route.fulfill() responds in place of the server, and route.abort() cuts it off. context.route sets a route for all pages of a context, including pop-up windows.

A URL pattern is a glob string or a regular expression. A single asterisk * matches any characters except /, and a double ** matches those too; the pattern must match the whole URL. So **/api/tasks catches both the production host and a test environment at a different address.

typescripta stub set before navigation
test('the list comes from a stub', async ({ page }) => {  // set the route before navigating  await page.route('**/api/tasks', async (route) => {    await route.fulfill({      json: [{ id: 1, title: 'Buy coffee', done: false }],    });  });   await page.goto('/tasks');  await expect(page.getByText('Buy coffee')).toBeVisible();});
GoalCall
Respond with a stub, no networkroute.fulfill({ json })
Let a request through, with changesroute.continue()
Return the real response with a modified bodyroute.fetch(), then route.fulfill({ response, json })
Block a requestroute.abort()
Respond with an error coderoute.fulfill({ status: 500 })

You can fetch the real response, modify it and return it: route.fetch() sends the request to the server, and route.fulfill sends the page a modified copy.

typescriptmodifying the real response
await page.route('**/api/tasks', async (route) => {  const response = await route.fetch();  const tasks = await response.json();  tasks.push({ id: 42, title: 'Task from the test', done: true });  await route.fulfill({ response, json: tasks });});

An action in the interface often triggers a background request. Create the response promise before the action and get the result after it, with page.waitForResponse().

typescriptwaiting for a background request
const responsePromise = page.waitForResponse('**/api/tasks');await page.getByRole('button', { name: 'Refresh' }).click();const response = await responsePromise;expect(response.status()).toBe(200);

A series of requests, for example when a page makes dozens of them, can be replayed from a HAR (HTTP Archive) file: the update: true option of page.routeFromHAR records the responses to the file, and later runs replay them without it.

What exactly to check in an API (schemas, status codes, authorisation, negative cases) is covered in the “API testing” reference. The methods and status codes themselves are in the “HTTP and REST” reference.

Section sources

the section is written from these pages

Configuration and projects

The playwright.config.ts file in the project root controls how tests behave: the test directory, the number of parallel workers, retries for failed tests, browsers, and starting the app before a run. Projects let you run the same tests in different browsers and environments.

Main options

A minimal config sets the test directory, parallelism, retries and the report. Values based on process.env.CI let one file serve both local runs and CI.

typescriptplaywright.config.ts
import { defineConfig } from '@playwright/test'; export default defineConfig({  // test directory, relative to the config  testDir: 'tests',  // run all tests in parallel, not just files  fullyParallel: true,  // retries are useful in CI; locally they hide flakiness  retries: process.env.CI ? 2 : 0,  // one worker in CI: predictable order  workers: process.env.CI ? 1 : undefined,  reporter: 'html',  use: {    baseURL: 'http://localhost:3000',    // trace for debugging failed retries    trace: 'on-first-retry',  },});
OptionWhat it doesDefault
testDirdirectory with test filesthe config file’s directory
fullyParallelall tests in all files run in parallelfalse — only files run in parallel
retrieshow many times to retry a failed test0
workersnumber of parallel workershalf of the logical cores
reporterreport format for the runlist, or dot in CI
globalTimeouttime limit for the whole runnone
webServerstarts the app before the testsnone
projectslist of projectsnone

Context settings

The use block holds the settings of the browser context — the environment a page opens in: base URL, window size, debugging artifacts. They apply to all tests until a project or a file overrides them.

OptionWhat it doesDefault
baseURLbase for relative paths such as page.goto('/login')none
tracerecords a trace for Trace Vieweroff
screenshotscreenshot after the testoff
videovideo recording of the testoff
headlessbrowser without a windowtrue
viewportpage window size{ width: 1280, height: 720 }
localeenvironment language and date formaten-US
timezoneIdtime zone, for example Europe/Parisnone

Recording modes: for trace and video — off, on, retain-on-failure, on-first-retry; for screenshot — off, on, only-on-failure, on-first-failure. Files go to the test-results directory. For reading traces, see the “Debugging and tracing” section.

Timeouts

Playwright Test has separate timeouts for the test, assertions, actions and the whole run. The time spent in fixtures and the beforeEach hook counts towards the test timeout.

TimeoutDefaultWhat it limits
test, timeout30,000 msthe whole test: body, fixtures, beforeEach
assertion, expect.timeout5,000 mseach expect assertion
action, use.actionTimeoutnoneeach action: click, typing
navigation, use.navigationTimeoutnoneeach navigation, such as page.goto
global, globalTimeoutnonethe entire run

To change the timeout of a single test, use test.setTimeout() or test.slow(), which triples the current value. Actions and navigations are not limited at all by default: a test fails on its own timeout, not on a click timeout. Raise action timeouts only for a good reason: flakiness is fixed by auto-waiting (see the “Actions and auto-waiting” section).

Projects

A project is a group of tests with its own configuration: a name, use settings and a file filter. Projects let the same test files run in different browsers and environments. Shared use settings apply to all projects; a setup project runs first, and the other projects then run in parallel.

A dependency makes the setup project run before the others; the browser projects run in parallel.

The browser or emulated device comes from the devices registry: devices['Desktop Chrome'] or devices['iPhone 12']. A branded browser is selected through a channel: channel: 'chrome' or channel: 'msedge'. The dependencies option lists projects that must pass first: until the setup project’s tests pass, the others do not start.

typescriptplaywright.config.ts excerpt
import { defineConfig, devices } from '@playwright/test'; export default defineConfig({  projects: [    // one-off preparation, such as authentication    { name: 'setup', testMatch: /.*\.setup\.ts/ },    {      name: 'chromium',      use: { ...devices['Desktop Chrome'] },      dependencies: ['setup'],    },    {      name: 'firefox',      use: { ...devices['Desktop Firefox'] },      dependencies: ['setup'],    },    {      name: 'Mobile Safari',      use: { ...devices['iPhone 12'] },      dependencies: ['setup'],    },  ],});

Environments and test selection

All projects run by default; run a single one with the --project=firefox flag. Projects are handy for different environments: staging and production differ in baseURL and in the number of retries. They also split the test suite: the testMatch and testIgnore filters select files by name.

typescriptplaywright.config.ts excerpt
export default defineConfig({  projects: [    // quick run of critical scenarios    { name: 'Smoke', testMatch: /.*smoke\.spec\.ts/, retries: 0 },    // everything else, with retries    { name: 'Default', testIgnore: /.*smoke\.spec\.ts/, retries: 2 },  ],});

Starting the app before tests

The webServer option starts the app before the run: the runner waits until url responds with a 2xx, 3xx or 400–403 status, then runs the tests and stops the process afterwards. Several servers, such as a frontend and a backend, are configured with a webServer array. The command inherits the environment with the PLAYWRIGHT_TEST=1 variable added; startup is limited by a timeout, 60,000 ms by default. Together with baseURL, tests can use relative paths.

typescriptplaywright.config.ts excerpt
import { defineConfig } from '@playwright/test'; export default defineConfig({  webServer: {    command: 'npm run start',    url: 'http://localhost:3000',    // locally, reuse your own server; in CI, start a new one    reuseExistingServer: !process.env.CI,    // the build can take more than a minute    timeout: 120 * 1000,  },  use: {    baseURL: 'http://localhost:3000',  },});

Overriding in a file

Settings take precedence in this order: config, then project, then file and individual test. In a file or inside test.describe, test.use({...}) overrides options; the value undefined restores the setting from the config.

typescripttests/cart.spec.ts
import { test, expect } from '@playwright/test'; // the locale applies to the whole filetest.use({ locale: 'fr-FR' }); test('cart', async ({ page }) => {  await page.goto('/cart');  await expect(page).toHaveTitle(/Panier/);});

Section sources

the section is written from these pages

Debugging and tracing

Three tools show why a test fails. Playwright Inspector steps through a test, UI Mode replays a run with DOM snapshots and an action log, and a trace saves the same information to a file for analysis after the run. The test generator can record a test’s steps.

During a run, debug in Inspector or UI Mode; after a run, use the trace. The tools do not exclude each other: UI Mode records a trace for every test itself.

Step-by-step debugging in Inspector

The --debug flag opens Playwright Inspector and puts the run into debug mode: the browser starts with a window (headed) and the default timeout is disabled. The test runs one action at a time: the current step is highlighted in the code, and the matched element in the browser.

bashin the project directory
npx playwright test --debug# a single test starting at line 10npx playwright test example.spec.ts:10 --debug# one project from the configurationnpx playwright test --project=chromium --debug

The Pick Locator button suggests a robust locator: hover over an element, and Playwright proposes a locator based on role, text or test id and highlights the matches. The field next to the button shows the locator of the current step — you can edit it and see the highlight in the browser straight away. The actionability log explains what happened to the element: whether it was found by the locator, and whether it is visible, enabled, stable and scrolled into view.

javascripttest file
test('cart adds up items', async ({ page }) => {  await page.goto('https://example.com/cart');  // execution stops here, before the click  await page.pause();  await page.getByRole('button', { name: 'Pay' }).click();});

The page.pause() method stops the test at a chosen point, so you do not have to step through every action by hand. Run the test with --debug and click Resume — execution continues only up to the pause.

UI Mode

UI Mode opens with npx playwright test --ui. On the left is the test tree with a filter by name, tag, project and status (passed, failed, skipped); on the right is the trace of the selected run, and for a failed test, a tab with the error message and the source line. Hover over an action in the timeline to see a DOM snapshot of the page at that moment; next to it are tabs for actions, the network and the browser console.

Watch mode reruns a test when a file changes — turn it on with the eye icon next to the test name. The DOM snapshot can be popped out into a separate window, where you can open DevTools and edit a locator against the snapshot with the Pick Locator button.

ToolHow to startWhen it helps
Playwright Inspector--debugstep by step, editing locators
UI Mode--uirunning, filters, watching files
Trace viewershow-traceanalysing a failed test, including one from CI
codegencodegenrecording actions and generating a test

Tracing

A trace records every action of a test: the locator and duration, DOM snapshots before, during and after the action, a screencast, console messages, and network requests with headers and bodies. Tracing is off by default (trace: "off"). To debug tests that fail in CI, turn it on together with retries: trace: "on-first-retry" and retries: 1 — a recording is made only on the first retry of a failed test.

typescriptplaywright.config.ts
export default defineConfig({  retries: 1,  use: {    trace: "on-first-retry",  },});
trace valueWhat is recorded
on-first-retrythe first retry of a failed test
on-all-retriesall retries
retain-on-failureevery test, but the file is deleted for passing ones
onevery test; slows the run down
offnothing

Open a recording with npx playwright show-trace and the path to the trace.zip file in the test-results directory, or through the HTML report: npx playwright show-report, then the trace icon next to the test. The same viewer is available at trace.playwright.dev: the file is loaded into the browser in full and is not sent anywhere.

bashin the project directory
npx playwright show-trace test-results/cart/trace.zip# or through the HTML reportnpx playwright show-report

Recording steps: codegen

The test generator turns your actions into code. The npx playwright codegen command opens a browser and an Inspector window: click and fill in fields, and the steps appear in the window as lines of code that you can copy to your editor with one button. Buttons on the toolbar add three assertions: element visibility, its text and the value of a field (see the “Assertions (expect)” section).

bashin the project directory
npx playwright codegen https://example.com# record for a mobile devicenpx playwright codegen --device="iPhone 13" https://example.com

Pick Locator works in codegen too: hover to see the locator under each element, and a click moves the locator into a field where you can refine it. The generator supports emulation: --viewport-size sets the viewport, --device the device, --color-scheme the theme, and --timezone, --geolocation and --lang the time zone, coordinates and language. The --save-storage=auth.json option saves cookies and localStorage at the end of the session, so you can continue recording already signed in.

Browser console and API logs

In debug mode with the PWDEBUG=console environment variable, the playwright object is available in the browser’s DevTools console; open DevTools yourself in the browser window. They show the DOM tree, console messages and network activity. A detailed API log is enabled with the DEBUG=pw:api variable; in PowerShell, set the variable with $env:PWDEBUG="console".

bashin the project directory
PWDEBUG=console npx playwright testDEBUG=pw:api npx playwright test

In VS Code, debugging is handled by the Playwright extension: breakpoints, error messages with a full call log, and running in debug mode by right-clicking a test.

If a test fails only in CI, record a trace on the first retry and analyse it locally — see the “Running in CI” section. For typical error messages, see the “Common errors and diagnostics” section.

Section sources

the section is written from these pages

Running in CI

In CI, Playwright tests are run by npx playwright test on an agent with browsers installed. For GitHub Actions, the ready-made workflow from npm init playwright@latest is enough, and a large test suite runs faster when sharded across several jobs with a combined report.

Three commands do the setup and the run: npm ci installs the project’s dependencies, npx playwright install --with-deps downloads the browsers and the Linux system packages, and npx playwright test runs the tests. On an agent without browsers, tests fail at the very first launch.

bashon the CI agent
npm cinpx playwright install --with-depsnpx playwright test

A ready-made workflow for GitHub Actions

When you create a project with npm init playwright@latest, you can add a workflow right away: the initialiser puts a playwright.yml file in .github/workflows. Tests run on every push and pull request to the main and master branches, and the report is uploaded as an artifact even if the tests fail.

yaml.github/workflows/playwright.yml
name: Playwright Testson:  push:    branches: [main, master]  pull_request:    branches: [main, master]jobs:  test:    runs-on: ubuntu-latest    steps:      - uses: actions/checkout@v6      - uses: actions/setup-node@v6        with:          node-version: lts/*      - name: Install dependencies        run: npm ci      - name: Install Playwright Browsers        run: npx playwright install --with-deps      - name: Run Playwright tests        run: npx playwright test      - uses: actions/upload-artifact@v5        if: ${{ !cancelled() }}        with:          name: playwright-report          path: playwright-report/          retention-days: 30

The if: ${{ !cancelled() }} condition runs the step even when tests fail: that is exactly when you need the failure report. The same rule applies to uploading blob reports when sharding.

Settings for CI

Environment-dependent settings are driven by the CI variable: in CI, retrying failed tests is fine, while locally retries hide flakiness; parallelism is reduced in CI, and a run that contains a committed test.only fails as a whole.

typescriptplaywright.config.ts
export default defineConfig({  // a committed test.only fails the run in CI  forbidOnly: !!process.env.CI,  // retries make sense in CI; locally they hide flakiness  retries: process.env.CI ? 2 : 0,  // one worker in CI: stability matters more than speed  workers: process.env.CI ? 1 : undefined,  // end the run with a report instead of a hung job  globalTimeout: 60 * 60 * 1000,});

Without globalTimeout, a run has no upper limit: a hung test suite is killed by the CI job’s own limit in the middle of the run, with no report. With globalTimeout, Playwright stops the run itself, and reporters have time to write the report. Leave the CI job without timeout-minutes, or set a value well above the global timeout.

Choose the reporter by environment: locally, a run prints the detailed list reporter; in CI, the concise dot reporter. A web interface needs HTML, and when sharding in CI you use blob instead.

typescriptplaywright.config.ts
export default defineConfig({  // blob is needed to merge the report from shards  reporter: process.env.CI ? 'blob' : 'html',});

Playwright Docker image

The official mcr.microsoft.com/playwright image already contains the browsers and system dependencies; the @playwright/test package is not included and is installed with npm ci together with the project. Pin the tag to the Playwright version and the Ubuntu distribution: noble is 24.04.

yamljob in a container
jobs:  test:    runs-on: ubuntu-latest    container:      image: mcr.microsoft.com/playwright:v1.65.0-noble      options: --user 1001    steps:      - uses: actions/checkout@v6      - name: Install dependencies        run: npm ci      - name: Run Playwright tests        run: npx playwright test

A job in a container does not clutter the runner with dependencies and gives screenshot tests the same environment every time. options: --user 1001 runs the container as a non-root user: as root, Chromium disables its sandbox. For manual runs, the image has a separate pwuser user.

Sharding and merging reports

The --shard=x/y flag splits tests into y shards, and shard x runs only its own part. Each shard is a separate CI job, and four jobs with --shard=1/4 … 4/4 finish the suite about four times faster. fullyParallel: true makes the split even: without it, tests are split by file, and a file with a hundred tests overloads one shard.

This is how a large test suite finishes four times faster than in a single job.

Each shard writes a blob report — a file with all the tests, their results and attachments such as traces. Blob report names contain the shard number, so the files do not conflict; by default they go to the blob-report directory. The npx playwright merge-reports command builds the final HTML.

yamlpart of a job with a matrix
strategy:  fail-fast: false  matrix:    shardIndex: [1, 2, 3, 4]    shardTotal: [4]steps:  - name: Run Playwright tests    run: >-      npx playwright test      --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}  - name: Upload blob report    if: ${{ !cancelled() }}    uses: actions/upload-artifact@v5    with:      name: blob-report-${{ matrix.shardIndex }}      path: blob-report      retention-days: 1

The merge job starts after all the shards and collects their artifacts into one directory: merge-multiple: true puts the files together. It needs the sources and npm ci, because merge-reports is run from the installed @playwright/test package. It runs even when shards fail — otherwise the failure report would not be built.

yamlreport merge job
merge-reports:  if: ${{ !cancelled() }}  needs: [playwright-tests]  runs-on: ubuntu-latest  steps:    - uses: actions/checkout@v6    - uses: actions/setup-node@v6      with:        node-version: lts/*    - name: Install dependencies      run: npm ci    - uses: actions/download-artifact@v5      with:        path: all-blob-reports        pattern: blob-report-*        merge-multiple: true    - name: Merge into HTML Report      run: npx playwright merge-reports --reporter html ./all-blob-reports    - uses: actions/upload-artifact@v5      with:        name: html-report        path: playwright-report        retention-days: 14

Artifacts: the report and traces

Two things are read from artifacts: the HTML report and the traces of failed tests. Download the report as a zip file from the job’s page, unpack it, and show it with npx playwright show-report and the directory name — double-clicking the file will not work, because the report needs a web server.

bashafter unpacking the artifact
npx playwright show-report downloads/report

A failed test’s trace opens from the report with the icon next to the file name; for how to read it, see the “Debugging and tracing” section. With trace: "on-first-retry", a trace is recorded on the first retry of a failed test, so enable retries in CI along with it. Trace files are kept in test-results and are included in the blob report automatically.

Workflow syntax, runners and caching are the same for any pipeline: see the CI/CD reference, the “Workflow syntax and .gitlab-ci.yml” section. For typical run failures, see the “Common errors and diagnostics” section.

Section sources

the section is written from these pages

Common errors and diagnostics

A failing Playwright test is almost always reproducible: a timeout expired, a locator matched several elements, or the browser lacks system libraries. Start with the HTML report and the trace of the failed test: they show the step, the DOM snapshot and the action log. Then find your symptom in the list below.

Where to start

The error message already names the problem: a timeout, a locator or an assertion, and the call log under it lists what Playwright was waiting for. If the facts are not enough, the report and the trace supply them.

  1. npx playwright show-report — the HTML report of the last run: test steps, the error, a screenshot and the trace; it opens automatically on failure;
  2. npx playwright test --trace on — rerun with a trace for every test; open the recording with npx playwright show-trace;
  3. npx playwright test --workers=1 — run in a single worker: if the failure disappears, the tests depend on each other or on shared data.

Test timeout of 30000ms exceeded.

Playwright Test has separate timeouts, and the message shows which one expired. The test timeout — 30,000 ms by default — limits the test body together with fixtures and the beforeEach hook. The assertion timeout — 5,000 ms — applies to retrying expect assertions. Actions and navigations have no limit of their own: a click or page.goto waits to the end and fails on the test timeout.

Raise the limit only if the step really is slow: test.slow() triples the timeout of one test, and each assertion has its own timeout argument. If the element never appears, a longer timeout will not help — find the step in the trace: its log shows which actionability checks the click passed and which one it got stuck on. For how to record a trace, see the “Debugging and tracing” section.

typescriptexample.spec.ts
test('report takes a long time to build', async ({ page }) => {  test.slow(); // triples this test’s timeout  await page.goto('https://example.com/reports');  await expect(page.getByText('Done')).toBeVisible({    timeout: 15_000,  });});

strict mode violation

A locator is strict: actions and assertions require exactly one element, but the query matched several — the matches are listed in the message. First count how many elements match the query with a toHaveCount assertion, then narrow the query with filter or refine the role and name.

typescriptrefining a locator
// how many buttons match the queryawait expect(  page.getByRole('button', { name: 'Buy' }),).toHaveCount(3);// narrow down to one product cardconst card = page  .getByRole('listitem')  .filter({ hasText: 'Wool blanket' });await card.getByRole('button', { name: 'Buy' }).click();

The first(), last() and nth() methods turn off the strictness check and pick an element by position. With a guaranteed order that is acceptable, but if the page changes, the click lands on a different element — a unique locator is more reliable (see the “Locators” section).

Click does not go through: the element is covered

Before an action, Playwright runs actionability checks: the element is visible, not animating, enabled, and it is the one that receives the event, not an element on top of it. While the checks fail, the action waits — and fails on the test timeout, not on its own. A typical cause is a modal dialog or a loading indicator over the button: wait until the overlay disappears.

typescriptexample.spec.ts
// wait for the dialog to disappearawait expect(page.getByRole('dialog')).toBeHidden();await page.getByRole('button', { name: 'Save' }).click();

The browser does not start on Linux

A browser is installed with npx playwright install, but it needs the distribution’s libraries to run. The same command installs them with the --with-deps flag: it downloads the browser and installs packages with the system package manager, asking for administrator rights. For more on dependencies, see the “Installation and first run” section.

bashon the machine that runs the tests
npx playwright install --with-deps chromium

Passes locally, fails in CI

Compare the environments, not the test. Window: by default viewport is 1280×720, but with the value null it depends on the host window, and the page looks different on another screen. Locale and time zone: the interface may respond in a different language. Parallelism: tests run in several workers and may share server data.

typescriptplaywright.config.ts, use block
use: {  viewport: { width: 1280, height: 720 },  locale: 'en-GB',  timezoneId: 'Europe/London',},

Check with a single-worker run, --workers=1, then pin the settings in the configuration so that runs match. For running in CI, see the “Running in CI” section.

A flaky test

A flaky test fails and passes without any change to the code. By default a failed test is not retried; the retries option sets the number of retries, and a test that passes on a second attempt is marked flaky in the report. testInfo.retry gives the attempt number inside a test, for example to clear a server cache before a retry.

typescriptplaywright.config.ts
export default defineConfig({  retries: 2,});

A retry is a safety net, not a cure: look for the race condition. Each test has its own browser context with clean cookies and storage, but data on the server is shared: create it for each test with an API request and do not depend on the order of execution.

Instead of pauses, wait for the data to appear with a retrying expect assertion. Dependent tests can be grouped with serial mode, test.describe.configure({ mode: 'serial' }) — they run together and are retried together, but it is more reliable to make them independent.

Symptoms and what to do

A summary of the section: from symptom to cause and first step.

SymptomCauseWhat to do
Test timeout of 30000ms exceeded.the test timeout expiredtest.slow() or test.setTimeout(); find the slow step in the trace
in the log, expect.toHaveText with timeout 5000msthe assertion did not wait for the elementcheck the locator; for slow loading, give the assertion its own timeout
strict mode violationseveral elements match the locatornarrow the query with a filter, or a role and name
a click does not go through on a visible elementthe element is covered by another onewait for toBeHidden on the overlay
the browser does not start on Linuxsystem libraries are missingnpx playwright install --with-deps
passes locally, fails in CIdifferent window, locale, data or parallelismpin viewport, locale, timezoneId; check with --workers=1
the test is marked flakypassed only on a retryisolate data; look for the race condition in the trace
the whole run is aborted on a timeoutglobalTimeout expiredraise the limit in the configuration or remove it

If your symptom is not in the table, turn on tracing with the --trace on flag: the DOM snapshot in the recording shows how the page differed from what you expected.

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Playwright 1.65: the latest release is 1.65.0, published on 5 November 2026. Minor versions ship roughly once a month, and each release is tied to its own builds of Chromium, Firefox and WebKit.

VersionRelease dateBrowsers
1.655 November 2026Chromium 158.0.8127.18, Firefox 159.0, WebKit 27.2
1.647 October 2026 (patch 1.64.1 on 14 October)Chromium 156.0.8078.4, Firefox 157.0, WebKit 27.2
1.634 September 2026Chromium 153.0.8010.12, Firefox 155.0, WebKit 26.6

Patch releases with bug fixes appear between minor releases: 1.64.1, for example, fixed only two bugs and brought no new browsers. In addition to its own browsers, each release is tested against the stable channels of Google Chrome and Microsoft Edge; their versions are listed alongside on the release notes page.

What changed in 1.65

  • Running under Bun: bunx --bun playwright test. The --bun flag is required; without it the command runs on Node.js. Bun transpiles TypeScript itself, so Babel and the transpilation cache are not needed; there is no watch mode, --tsconfig and the JSX options in tsconfig.json have no effect, and error stacks have no async frames.
  • The failures reporter prints failures and successful retries as they happen, without a progress indicator, and ends with a summary. The onlyFailures option on the HTML, JSON and JUnit reporters keeps only unexpected results, flaky tests and interrupted tests in the report. For building reports in CI, see “Running in CI”.
  • A built-in -exclusive- lock (test lock): a test that holds it does not start while another test is running, while the remaining tests keep running in parallel. Named locks were introduced in 1.63.
  • The test.skip(), test.fixme(), test.fail() and test.slow() annotations accept only a description, which is recorded in the test annotation.
typescriptplaywright.config.ts
import { defineConfig } from '@playwright/test'; export default defineConfig({  reporter: [    ['failures'],    ['html', { onlyFailures: true }],  ],});

What changed in 1.64

  • WebMCP (experimental): page.webmcp gives access to the tools that a page registers through the browser API of the same name, and they are called like any other part of the application; the browser must be launched with the --enable-features=WebMCP flag.
  • Video recording: a new fps option (25 frames per second by default; Firefox and WebKit still record at most 25) and CSS styling of the action marker, highlight and caption through the style option; the codec changed from VP8 to VP9.
  • Test runner: the default: false option on a project excludes it from a normal run, so it only runs when requested explicitly with --project; the --shuffle flag randomises test order to uncover accidental dependencies between tests.

Deprecated and removed

ChangeSinceWhat to do
Node.js 20 is no longer tested1.65use 22, 24 or 26
TypeScript class fields follow the useDefineForClassFields option from tsconfig.json (for target ES2022 and newer); an initialiser that reads a constructor parameter fails1.65move the initialisation into the constructor or set "useDefineForClassFields": false
Cookies are matched according to RFC 6265: host-only cookies are not sent to subdomains, and Path=/api does not match /apiv21.65recheck tests that read cookies by URL
Credentials from the proxy option answer only the proxy’s own requests1.65for authentication on a site, use httpCredentials
Text that the browser does not render has been removed from accessible names and aria snapshots1.65recheck getByRole with name, and aria snapshots
A sharded run fails with No tests found if no shard found any tests1.65allow it with the --pass-with-no-tests flag
The blob reporter once again cleans its directory before writing (in 1.64 it left other files in place)1.65do not keep unrelated files in the report directory
Screen from device descriptors: window.screen and media queries now see the emulated screen size1.64turn it off with screen: undefined in the configuration
The --update-snapshots=missing mode finishes the run successfully if the tests only created snapshots1.64for the previous behaviour, use the default mode
The fontSize parameter in video styling is deprecated1.64CSS strings in the style option
The @playwright/experimental-ct-react, -ct-react17 and -ct-vue packages are no longer updated1.63the stories model introduced in 1.62
Ubuntu 20.04 is not supported1.63Ubuntu 22.04 and newer

How to update

Update the package and the browsers together, with the same pair of commands used for installation (see “Installation and first run”). To keep versions identical on every machine, pin a minor version in CI rather than using latest:

bashin the project folder
npm install -D @playwright/test@1.65npx playwright install --with-deps

npx playwright --version shows the installed version; the full list of changes in each release is on the release notes page.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Playwright” topic
13 sections
Another reference · Backend

HTTP and REST

Verified 1 Nov
All references · 61