The suite had 400 Playwright tests and a reputation. Developers called it "the flaky one" and reran red builds until they turned green. When someone finally read the failures, most traced back to three habits: CSS selectors copied from DevTools, a waitForTimeout(3000) in every other test, and tests that shared one logged-in user and quietly changed each other's data.
None of those are Playwright problems. They're suite-design problems, and they're fixable.
Playwright best practices come down to five habits: locate elements by role, label or test id instead of CSS; use web-first assertions and auto-waiting instead of sleeps; isolate every test; put setup in fixtures and page objects; and record traces on CI. Follow them and Playwright alone is enough for most web teams.
Key takeaways
- Use
getByRole,getByLabelandgetByTestId. CSS and XPath tied to the DOM structure break first. - Never use fixed waits. Locators auto-wait, and
await expect(...)assertions retry until they pass or time out. - Make tests independent: fresh browser context per test, shared login through a saved storage state, data each test owns.
- Fixtures handle setup and teardown; page objects hold page knowledge. Use both, and keep page objects thin.
What makes a Playwright suite last?
A Playwright suite lasts when a UI change breaks only the tests that should break. Most long-term pain comes from tests that depend on DOM structure, timing or each other.
Playwright's own best practices page starts with the principle that matters most: test user-visible behaviour, not implementation details such as function names, CSS classes or data structures. Every practice below follows from that.
If you're still choosing a framework, our comparison of test automation frameworks covers where Playwright fits. All code below is TypeScript with @playwright/test, written for a hypothetical app; URLs, labels and test ids are illustrative.
Which Playwright selectors are most reliable?
Use locators that match how a user, or an assistive technology, finds the element. In order of preference:
getByRolewith an accessible name, for buttons, links, headings, checkboxes and form controls.getByLabelfor form fields,getByPlaceholderwhen there's no label.getByTextfor non-interactive content.getByTestIdwhen there's no stable user-facing handle.- CSS or XPath only as a last resort.
// Illustrative example
await page.getByRole('button', { name: 'Place order' }).click();
await page.getByLabel('Email address').fill('ana@example.com');
await expect(page.getByRole('heading', { name: 'Order confirmed' })).toBeVisible();
// Narrow the search with chaining and filtering
const row = page.getByRole('row').filter({ hasText: 'Invoice #1042' });
await row.getByRole('button', { name: 'Download' }).click();
// Fragile: tied to DOM structure and styling
await page.locator('div.checkout > form button.btn-primary:nth-child(2)').click();
Role-based locators double as a light accessibility check: if you can't find a button by role and name, a screen reader user probably can't either.
When should you use data-testid?
Use test ids for elements with no stable accessible name: icon-only controls you can't relabel, repeated cards, canvas wrappers, or text that changes with locale. Agree a naming convention with developers and treat ids as a contract, not decoration.
getByTestId reads data-testid by default. If your app uses a different attribute, set it once in config:
// playwright.config.ts (illustrative)
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: { testIdAttribute: 'data-qa' },
});
Don't put test ids on everything. If every locator is a test id, your tests no longer notice when a button loses its label.
Generate first drafts of locators with npx playwright codegen <url> or the VS Code extension, then edit them toward roles and labels.
How do you avoid flaky waits in Playwright?
Delete every waitForTimeout. Playwright locators auto-wait for elements to be visible, stable, enabled and able to receive events before acting. Fixed sleeps are either too short (flaky) or too long (slow).
Use web-first assertions, which retry until the condition holds or the timeout passes:
// Good: waits and retries
await expect(page.getByText('Payment received')).toBeVisible();
await expect(page.getByRole('status')).toHaveText('Saved');
await expect(page).toHaveURL(/\/orders\/\d+/);
// Bad: checks once, right now, and doesn't wait
expect(await page.getByText('Payment received').isVisible()).toBe(true);
When you need to wait for the app rather than an element, wait for the thing that matters, such as a specific network response:
const saved = page.waitForResponse(r => r.url().includes('/api/profile') && r.ok());
await page.getByRole('button', { name: 'Save' }).click();
await saved;
Use soft assertions when you want to check several things in one run without stopping at the first failure: await expect.soft(page.getByTestId('status')).toHaveText('Success').
How do you keep Playwright tests isolated?
Each test should run alone, in any order, on any worker. Playwright gives every test a fresh browser context by default, so cookies and storage don't leak. Your job is to keep data and login from leaking instead.
Log in once, reuse the state. Playwright's authentication docs recommend a setup project that signs in and saves the storage state, which other projects then load:
// tests/auth.setup.ts (illustrative)
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!);
await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('navigation')).toBeVisible();
await page.context().storageState({ path: authFile });
});
// playwright.config.ts (excerpt)
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],
Keep the .auth folder out of git, and read credentials from CI secrets, never from the test file.
Own your data. Tests that edit data should create it first, ideally through an API call, and clean it up after. Two tests editing the same "test customer" in parallel is a classic source of failures that only happen on CI.
Mock what you don't control. Use page.route to stub third-party services such as payment widgets, maps or analytics, so their outages don't fail your build:
await page.route('**/api/exchange-rates', route =>
route.fulfill({ status: 200, json: { usd: 1, eur: 0.92 } }),
);
What are Playwright fixtures and when should you use them?
Fixtures are Playwright's answer to beforeEach and afterEach. A fixture sets something up, hands it to the test, and tears it down after, and a test only gets the fixtures it asks for by name. The fixtures docs show the pattern:
// fixtures.ts (illustrative)
import { test as base } from '@playwright/test';
import { CartPage } from './pages/cart-page';
type MyFixtures = {
cartPage: CartPage;
};
export const test = base.extend<MyFixtures>({
cartPage: async ({ page, request }, use) => {
const cart = await request.post('/api/test/carts', { data: { items: ['sku-123'] } });
const { id } = await cart.json();
const cartPage = new CartPage(page);
await cartPage.open(id);
await use(cartPage); // the test runs here
await request.delete(`/api/test/carts/${id}`); // teardown
},
});
export { expect } from '@playwright/test';
// cart.spec.ts
import { test, expect } from './fixtures';
test('applies a discount code', async ({ cartPage }) => {
await cartPage.applyCode('WELCOME10');
await expect(cartPage.total).toHaveText('$90.00');
});
A few rules that keep fixtures manageable:
- Test-scoped by default. Use
{ scope: 'worker' }only for expensive, read-only resources, such as a seeded account per worker. - Use
{ auto: true }sparingly, for things every test needs, such as attaching logs on failure. - Combine fixture files with
mergeTestsinstead of one giant fixtures module. - Teardown belongs after
use(), so it runs even when the test fails.
Should you use the page object model with Playwright?
Yes, for any suite bigger than a handful of tests. A page object keeps the knowledge of one page (its locators and common actions) in one place, so a renamed button means one edit, not forty. Playwright's POM docs use plain classes:
// pages/cart-page.ts (illustrative)
import { type Page, type Locator } from '@playwright/test';
export class CartPage {
readonly page: Page;
readonly codeInput: Locator;
readonly applyButton: Locator;
readonly total: Locator;
constructor(page: Page) {
this.page = page;
this.codeInput = page.getByLabel('Discount code');
this.applyButton = page.getByRole('button', { name: 'Apply' });
this.total = page.getByTestId('cart-total');
}
async open(cartId: string) {
await this.page.goto(`/cart/${cartId}`);
}
async applyCode(code: string) {
await this.codeInput.fill(code);
await this.applyButton.click();
}
}
Keep page objects thin:
- Locators and actions, not assertions. Expose locators like
totaland let the test assert on them, so each test reads as a clear check. - No hidden waits or retries. Locators already wait; extra logic hides real problems.
- Model components, not just pages. A header, a date picker or a data table used on many pages deserves its own object.
- Inject through fixtures, as above, so tests never call
new CartPage(page)themselves.
How should you configure Playwright for CI?
A sensible baseline, close to what npm init playwright generates:
// playwright.config.ts (illustrative)
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: process.env.CI ? 'blob' : 'html',
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
trace: 'on-first-retry',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});
Use the trace viewer, not videos, for debugging. The best practices page recommends traces on CI because they include a timeline, DOM snapshots and network requests. trace: 'on-first-retry' records only when a test fails and is retried, which keeps runs fast. Open a trace with npx playwright show-trace trace.zip or from the HTML report.
Treat retries as a signal, not a fix. Playwright marks a test that fails then passes on retry as "flaky". Track that list and fix it; don't let retries hide it.
Shard large suites across machines. Pass --shard=x/y and merge the blob reports into one HTML report, per the sharding docs:
# .github/workflows/e2e.yml (excerpt, illustrative)
strategy:
matrix:
shard: [1/4, 2/4, 3/4, 4/4]
steps:
- run: npx playwright install --with-deps
- run: npx playwright test --shard=${{ matrix.shard }}
# upload blob-report/ as an artifact, then in a final job:
# npx playwright merge-reports --reporter html ./all-blob-reports
With fullyParallel: true, Playwright distributes individual tests across shards rather than whole files, which balances shards better. Our CI/CD test automation page covers pipeline patterns beyond Playwright.
Lint your tests. A missing await is the most common silent bug in Playwright code. Enable the @typescript-eslint/no-floating-promises rule and run tsc --noEmit in CI.
A Playwright best practices checklist
| Area | Do | Avoid |
|---|---|---|
| Locators | getByRole, getByLabel, getByTestId | Long CSS chains, XPath, nth-child |
| Waiting | Auto-waiting, await expect(...), waitForResponse | waitForTimeout, manual polling |
| Isolation | Fresh context, saved storage state, own test data | Shared users editing shared records |
| Setup | Fixtures with teardown after use() | Long beforeAll blocks with hidden state |
| Structure | Thin page objects injected by fixtures | Assertions and retries inside page objects |
| Third parties | page.route mocks | Hitting real payment or map services |
| Debugging | Traces on first retry, HTML report | Screenshots alone, console.log hunts |
| Scale | fullyParallel, sharding, blob reports | One long serial job |
| Code quality | no-floating-promises, tsc --noEmit | Unchecked async code |
Where is Playwright alone enough, and where does it struggle?
Playwright alone is enough when developers or SDETs own the tests, the product is a web app, and tests live in the repository with code review. Follow the practices above and you get fast, stable, cross-browser tests with no licence cost. Playwright also now ships Test Agents (planner, generator and healer) for teams using coding agents, and our Playwright MCP guide covers agent-driven browser control.
It struggles in four situations, none of which better code fully solves:
- Non-coders own the journeys. QA analysts and product owners can't extend a TypeScript suite on their own.
- The UI changes every sprint. Good locators reduce breakage but don't remove it. Someone still updates page objects, and an agent healer's patches still need review.
- Journeys leave the browser. Playwright supports Chromium, Firefox and WebKit with mobile emulation; it doesn't drive native mobile or desktop apps.
- Nobody owns the infrastructure. Runners, sharding, report merging, secrets and flake tracking are all yours.
If those sound familiar, read about self-healing test automation and how teams move from manual to automation testing without a large SDET team.
Playwright and Robonito
Robonito is an agentic QA platform: AI agents create, run and maintain end-to-end tests. It's an option for the cases above where Playwright alone struggles, and it can sit next to a developer-owned Playwright suite.
- Plain-language authoring. In AI Studio you describe what to test, paste a URL or reference a Jira issue, and the agent works through the app step by step. It can also generate tests from requirement documents and Jira stories. You can record a flow in the desktop app or build no-code tests from reusable steps, with low-code extensions for advanced cases.
- Self-healing with a log. Steps adapt when labels, layouts or locators change, and healed steps are logged for review, so a heal never silently changes what a test checks.
- Evidence on every run. Parallel runs in isolated cloud workers keep video, network traces and an AI root cause for failures, with pass rates and trends across runs.
- Beyond the browser. Web is on every plan; mobile (Android and iOS), desktop and API testing are on Pro and Enterprise.
- CI and tools. Jenkins, GitHub Actions, GitLab CI, Azure DevOps and CircleCI, plus Jira and Slack, on Starter and above.
- Code when you want it. Robonito can generate executable code for test cases.
Pricing. Free is $0 with 100 test cases, web testing and self-healing. Starter is $20 a month and adds CI/CD, Jira and Slack. Pro is $199 a month and adds mobile, desktop and API. Enterprise is custom. Local runs are free on every plan. See pricing and the full Robonito vs Playwright comparison, or our Playwright alternative page.
Where it doesn't fit. If your developers are happy writing and reviewing Playwright tests for a web-only product, the practices in this post will serve you well and cost nothing in licences. Robonito isn't for unit or component tests, and the Free plan doesn't include CI integration.
with one journey your Playwright suite keeps breaking on, or .
Frequently asked questions
What are the most important Playwright best practices?
Locate elements by role, label or test id instead of CSS; use web-first assertions and auto-waiting instead of fixed sleeps; isolate every test with its own context and data; put setup in fixtures and page knowledge in page objects; and record traces on CI. Together these remove most flakiness and make UI changes cheap to absorb.
Should I use data-testid or getByRole in Playwright?
Prefer getByRole with an accessible name, because it matches how users find elements and catches missing labels. Use getByTestId when there's no stable user-facing handle, such as icon-only buttons or repeated cards. Agree test ids with developers as a contract, and change the attribute with testIdAttribute in config if needed.
Are Playwright fixtures better than beforeEach?
For most setup, yes. Fixtures are requested by name, so each test gets only what it needs, and teardown after use() runs even when the test fails. They also compose across files with mergeTests and can be worker-scoped for expensive resources. beforeEach is still fine for simple, file-local steps like navigating to a page.
Does Playwright need the page object model?
Not for a handful of tests, but yes once a suite grows. Page objects keep each page's locators and actions in one class, so a UI change means one edit. Keep them thin: locators and actions only, assertions in tests, and inject them through fixtures so tests stay short and readable.
How do I reduce flaky Playwright tests?
Remove fixed waits, use web-first assertions, isolate test data, mock third-party services with page.route, and run with a stable baseURL and environment. Record traces on first retry and track tests Playwright marks as flaky instead of relying on retries. Lint for missing await with no-floating-promises.
How do I run Playwright tests faster in CI?
Set fullyParallel: true, run multiple workers per machine, and shard the suite across machines with --shard=x/y. Use the blob reporter on each shard and npx playwright merge-reports to combine them. Install only the browsers you test, and log in once with a saved storage state instead of signing in in every test.
Keep the practices, lose the maintenance. to see a self-healing journey next to your Playwright suite, or .




