Playwright Best Practices, From the First Locator to the Flaky List
Retries can hide a flaky Playwright test for months. These Playwright best practices, from the first locator to the flaky list, name the failures they stop.
Playwright best practices are the habits that keep a suite trusted after its first few hundred tests, and Playwright’s own guide already gets them right. Find elements the way users see them, let assertions wait, keep every test isolated. Suites decay anyway, one reasonable shortcut at a time, because each shortcut saves its author time today and the team pays for it later.
If your suite passes on a retry every week and an upgrade is due, you’ve met that decay. Here is the list to bring to code review, with the failure every practice prevents and what Playwright 1.64 and 1.65 changed.
What you’ll learn
- Which locators survive a redesign, and which break on the first restyle
- How to log in once without tests leaking state into each other
- A CI config where retries collect evidence instead of hiding failures
- What changed in Playwright 1.64 and 1.65 that touches an existing suite
- Why a passing run can ship a screen your users can’t read
12 Practices and the Failures They Prevent
Start from Playwright’s best practices guide, which sets the philosophy. Test user-visible behavior, isolate every test and only test what you control. The table below turns that philosophy into practices in the order a suite needs them, assuming you already run test automation in a pipeline.
| Stage | Practice | Failure it prevents |
|---|---|---|
| Write | Locate by role and accessible name | A restyle breaks tests whose behavior never changed |
| Write | Use web-first assertions | A check reads the page before it is ready |
| Write | Mock third parties with page.route() | Somebody else’s outage turns your build red |
| Organize | A fresh context per test, login saved once | One test’s leftover state fails the next one |
| Organize | Fixtures for setup and teardown | Setup copied across files, drifting apart |
| Run in CI | forbidOnly on CI | A stray test.only ships a green run of one test |
| Run in CI | Retries with a trace on the first retry | A CI failure you can’t reproduce locally |
| Run in CI | failOnFlakyTests on CI | Retries hide a flaky test for months |
| Run in CI | Shard, then merge the reports | A suite too slow to run on every pull request |
| Maintain | Upgrade on purpose and read the breaking changes | An upgrade that breaks page objects overnight |
| Maintain | Run in shuffled order | Tests that pass only in their usual order |
| Maintain | Lint for floating promises | A missing await that makes a check do nothing |
Read the right-hand column as the reason to argue for each row in code review. A practice you can’t tie to a failure gets dropped the first week a deadline slips.
Locate Like a User
Find elements by what the user perceives, so a test breaks when behavior changes and survives when markup does. Playwright’s locator guide recommends role locators first, and text locators for non-interactive elements. Test ids are for when you can’t locate by role or text. The guide recommends against CSS and XPath, because the page’s Document Object Model (DOM) changes often. Locators are also strict, so an action on a locator that matches two elements throws instead of picking one.
// Survives a restyle: role plus accessible name
await page.getByRole('button', { name: 'Place order' }).click();
// Throws a strict mode violation: two rows have this button
await page.getByRole('button', { name: 'Add to cart' }).click();
// Narrow to one row, then act on it
await page
.getByRole('listitem')
.filter({ hasText: 'Product 2' })
.getByRole('button', { name: 'Add to cart' })
.click();
When text changes often, say in a translated app, use page.getByTestId() and agree the ids with the developers who own the markup. The attribute defaults to data-testid and can be changed with testIdAttribute in the config. Not sure which locator to use? Run npx playwright codegen against the page and use Pick Locator, which prefers role, text and test id locators.
Let Assertions Wait
A web-first assertion such as expect(locator).toBeVisible() retries until its condition holds or its timeout runs out. A manual check that awaits isVisible() reads the page once and returns, so it races the app. Playwright’s docs warn that non-retrying assertions can lead to a flaky test.
Playwright’s assertion timeout is 5 seconds by default, separate from the test timeout of 30 seconds. Raise one assertion’s timeout where the app is slow by design, instead of adding page.waitForTimeout(). For a condition outside the DOM, such as a job finishing on your API, poll it.
// Slow by design: give this one check longer than the 5-second default
await expect(page.getByText('Export ready')).toBeVisible({ timeout: 30_000 });
// Outside the DOM: poll your API until the job reports done
await expect.poll(async () => {
const response = await page.request.get('/api/jobs/42');
return (await response.json()).status;
}, { timeout: 60_000 }).toBe('done');
To retry a whole block of steps, use expect().toPass(), and give it a timeout of its own. Its default is 0, and it ignores your custom expect timeout, so a failing block retries until the test itself times out.
Isolate Every Test
Every test should be able to run alone, in any order, on any worker. Playwright already gives each test its own page and browser context, so cookies and storage start clean. The leaks come from what you add, such as a shared account or shared rows in a database.
Log in once per run, not once per test, with a setup project that saves the browser state. Playwright’s authentication guide recommends a playwright/.auth directory that you add to .gitignore. The setup test below uses relative URLs, so it assumes baseURL is set in the config.
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.TEST_USER_EMAIL!);
await page.getByLabel('Password').fill(process.env.TEST_USER_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('button', { name: 'Account' })).toBeVisible();
await page.context().storageState({ path: authFile });
});
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
use: { baseURL: 'http://localhost:3000' },
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
],
});
The same guide sets a limit. A single shared login works only while tests don’t change server-side state. Once one test edits a setting that another test reads, give each worker its own account. Then mock what you don’t own, so somebody else’s rates API going down is not your failure.
await page.route('**/api/exchange-rates', route =>
route.fulfill({ status: 200, json: { usd: 1, eur: 0.92 } }),
);
Organize With Fixtures and Projects
Put setup and teardown in a fixture, so they live in one place and run only for the tests that ask for them. A fixture runs everything before use() as setup and everything after it as teardown, and Playwright sets up only the fixtures a test names.
import { test as base } from '@playwright/test';
import { CartPage } from './cart-page';
export const test = base.extend<{ cartPage: CartPage }>({
cartPage: async ({ page }, use) => {
const cartPage = new CartPage(page);
await cartPage.goto();
await use(cartPage);
await cartPage.empty();
},
});
Keep page objects thin, a screen’s locators and actions and nothing else. Then use projects for everything that varies the run, such as browsers, devices and the setup step from the last section. Add a Firefox or WebKit project with the same storageState and dependencies, and every browser starts signed in.
Run It in CI: Shards, Retries, Traces
CI is where failures get ignored, so the config carries more weight here than anywhere else. The config below follows Playwright’s own configuration and CI guidance, plus one flag the docs’ example config leaves out.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
failOnFlakyTests: !!process.env.CI,
workers: process.env.CI ? 1 : undefined,
reporter: process.env.CI ? 'blob' : 'html',
use: {
trace: 'on-first-retry',
},
});
Each line closes one hole:
forbidOnlyfails the run if somebody leavestest.onlyin the code.retrieswithtrace: 'on-first-retry'gives every CI failure a trace you can open in the Trace Viewer, with a timeline, a DOM snapshot for each action and the network requests.failOnFlakyTests, available since Playwright 1.52, makes the run exit with an error when any test is marked flaky, meaning it failed first and passed on a retry. Without it, the retry passes and the first failure goes unread.workers: 1is what Playwright’s CI guide recommends for stability, unless you run a powerful self-hosted machine. Go wide with sharding across machines instead.
# On each of four CI machines
npx playwright test --shard=1/4
# In a final job, after downloading every blob-report
npx playwright merge-reports --reporter html ./all-blob-reports
Three 1.65 changes apply here, per the release notes:
- A new
failuresreporter prints failures and successful retries as they happen. - The HTML, JSON and JUnit reporters now take
onlyFailures: true. - A sharded run now fails with “No tests found” when no shard has a test, unless you pass
--pass-with-no-tests.
Maintain It on Purpose
Maintenance is the first practice to slip, because skipping it fails no test. Put the three jobs below on a calendar, or they don’t happen.
Upgrade on purpose. Playwright’s guide says to keep the dependency current so you test against new browser versions before your users get them. Read the breaking changes each time. Playwright 1.65 makes TypeScript class fields follow useDefineForClassFields from your tsconfig.json, which is on for ES2022 and later targets and when no target is set. With it on, a common page-object pattern now throws.
import type { Page, Locator } from '@playwright/test';
// Throws in 1.65 when useDefineForClassFields is on:
// the field initializer runs before the constructor
class LoginPage {
readonly submit = this.page.getByRole('button', { name: 'Submit' });
constructor(private readonly page: Page) {}
}
// Works: initialize in the constructor
class LoginPage {
readonly submit: Locator;
constructor(private readonly page: Page) {
this.submit = page.getByRole('button', { name: 'Submit' });
}
}
The release notes also allow a stopgap in tsconfig.json:
{
"compilerOptions": {
"useDefineForClassFields": false
}
}
The same release removes text the browser doesn’t render from accessible names, which can change what getByRole() with a name matches. Run the full suite on the upgrade branch before merging it.
Shuffle the order. Playwright 1.64 added npx playwright test --shuffle, which runs tests in a random order and prints the seed so you can replay it. A test that fails only when shuffled depends on another test. Our test automation best practices show why the default order hides those dependencies.
Lint the awaits. Playwright recommends the @typescript-eslint/no-floating-promises rule and tsc --noEmit on CI. A missing await before expect lets the test finish before the check runs.
Some tools promise to skip this work. Locator-based self-healing test automation patches a broken locator so the run stays green, which is why every patch needs a reviewer. A patched locator can point at the wrong button with total confidence.
Where a Green Run Lies
Look, every practice above makes a green run more trustworthy, and none makes it mean “the screen works”. A pass proves three things. Each locator resolved, each action passed Playwright’s actionability checks, and each assertion you wrote held. It proves nothing about what you didn’t assert.
We keep seeing bugs that a green Playwright run passes. Text gets cut off, or one element sits over another until the page is almost impossible to read. Playwright’s own definitions show why.
An element counts as visible when it has a non-empty bounding box and isn’t visibility:hidden, and an element at opacity:0 counts as visible. toHaveText() reads textContent by default, so text clipped by its container still matches. A click fails when another element covers its target, but an assertion doesn’t check for cover. All four screens below pass on Playwright 1.65.
| On the screen | What the test checked | Result |
|---|---|---|
| Total cut off by its container | toHaveText(/Total/) | Pass, the text is in the DOM |
| Error message at opacity 0 | toBeVisible() | Pass, it has a bounding box |
| Banner covering the total | toHaveText() on the total | Pass, nothing clicked it |
| White text on a white button | toBeEnabled() | Pass, the button is enabled |
Playwright has two partial answers. Visual comparisons with toHaveScreenshot() diff a screen against a baseline. Rendering varies from one machine to the next, down to the power source, so the docs say to compare in the environment that made the baseline. Aria snapshots with toMatchAriaSnapshot() assert the accessibility tree against a template, which catches a missing heading or button but not a clipped total.
Put screenshot comparisons on the handful of screens where money changes hands, and run them on one CI image. Then have a person on your team look at those screens every release, because a screenshot diff tells you a screen changed, not whether a customer can still read it.
Test the Flows Your Team Never Wrote Down
Your Playwright suite covers the flows your team wrote down, and every practice above is the cost of keeping it honest. The flows nobody wrote down cost nothing until one of them breaks in production. That gap is what our agentic testing platform is for. Pie explores your web app without a script and turns what it finds into tests, and since it’s AI-native, your engineers never write or maintain a locator for it.
Keep Playwright for the fast checks your engineers write against every pull request. Run Pie on a schedule for the journeys nobody scripted, like settings pages, filters and the paths between features.
Make Flaky Fail the Build This Week
Add failOnFlakyTests: !!process.env.CI to your config this week. The next CI build where a test passes only on a retry exits with an error, and the report’s flaky list becomes the backlog your retries were hiding. Fix the first test on it next sprint.
Test the Flows Your Suite Never Scripted
Settings, filters and the paths between features, tested daily, beside the Playwright suite you already run.