Playwright Made E2E Testing Tolerable. Don't Squander It.
Take a typical case, made up for illustration. About one CI run in eight failed on a flaky end-to-end test. The suite was full of two-second sleeps and selectors like .btn-primary:nth-child(2), and all four parallel workers shared one test account, so carts leaked between tests. Developers had learned to click “re-run” without looking.
Playwright removes most of the old reasons for flaky browser tests, as long as you let it. Below is how auto-waiting works, locators that survive a redesign, a light page-object pattern, isolation and saved authentication, network interception, and how Playwright compares with Cypress today.
- Your E2E suite has a “re-run failed” button that everyone presses
- Tests use
waitForTimeout(2000)as a workaround - Selectors look like
div.css-xj9q12 > span:nth-child(3) - One test leaves data that breaks the next one
Playwright's auto-waiting, role/label-based locators, network interception, and per-test browser context eliminate the four classic sources of flakiness.
Auto-Waiting Is the Default — Stop Helping It
Playwright actions run actionability checks before acting, and the checks depend on the action. A click waits for the element to be visible, stable, enabled and receiving events, while fill also needs it to be editable. You do not need waitForSelector before click. You do not need waitForTimeout after navigation. Web-first assertions (expect(locator).toBeVisible()) also auto-retry until they pass or time out.
import { test, expect } from '@playwright/test';
test('user can sign up', async ({ page }) => {
await page.goto('/signup');
await page.getByLabel('Email').fill('ada@example.com');
await page.getByLabel('Password').fill('correct horse battery');
await page.getByRole('button', { name: 'Create account' }).click();
// Auto-retries until visible or test timeout. No sleeps needed.
await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
await expect(page).toHaveURL(/\/dashboard$/);
});Locators That Survive a Redesign
Prefer locators that match what a user (or assistive tech) sees. Order of preference:
getByRole('button', { name })— semantic, accessible, refactor-proof.getByLabel,getByPlaceholder,getByText— for form fields and static content.getByTestId('...')— when no semantic anchor exists; pair with adata-testidin source.- CSS selectors — last resort.
Page Object Model — Light Version
Full POM ceremonies (one class per page, getters for every element) tend to ossify. The light POM that scales: a small per-page module exporting locators and the few cross-cutting actions that aren't one-liners.
// pages/login.ts
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly email: Locator;
readonly password: Locator;
readonly submit: Locator;
constructor(public readonly page: Page) {
this.email = page.getByLabel('Email');
this.password = page.getByLabel('Password');
this.submit = page.getByRole('button', { name: 'Log in' });
}
async loginAs(user: { email: string; password: string }) {
await this.page.goto('/login');
await this.email.fill(user.email);
await this.password.fill(user.password);
await this.submit.click();
}
}Test Isolation Done Right
flowchart LR
R[Test runner] -->|new BrowserContext| C1[Context 1<br/>cookies/storage]
R -->|new BrowserContext| C2[Context 2<br/>cookies/storage]
R -->|new BrowserContext| C3[Context 3<br/>cookies/storage]
C1 -.->|all isolated| API[(API + DB)]
C2 -.-> API
C3 -.-> API
Each Playwright test gets its own BrowserContext — cookies, localStorage, indexedDB scoped to the test. Combine with per-test data in the API/DB (unique emails, scoped tenants) and you get safe parallelism for free.
Authentication State Reuse
Logging in via the UI on every test is wasteful. Sign in once in a setup project, save the storage state, reuse across tests.
// playwright.config.ts
projects: [
{
name: 'setup',
testMatch: /.*\.setup\.ts/,
},
{
name: 'chromium',
// One shared login suits read-only tests. If tests change server data, give each worker
// its own account: a browser context isolates cookies, not your backend.
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],
// auth.setup.ts
import { test as setup } from '@playwright/test';
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_PASS!);
await page.getByRole('button', { name: 'Log in' }).click();
await page.waitForURL('/dashboard');
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});Network Interception
Stub flaky third-party calls without leaving the browser. page.route intercepts requests by URL pattern; you can mock, modify, or assert.
test('shows error when payments service is down', async ({ page }) => {
await page.route('**/api/payments/charge', route =>
route.fulfill({ status: 503, body: JSON.stringify({ error: 'unavailable' }) }));
await page.goto('/checkout');
await page.getByRole('button', { name: 'Pay' }).click();
await expect(page.getByRole('alert')).toContainText('try again');
});Cypress vs Playwright in 2026
| Concern | Playwright | Cypress |
|---|---|---|
| Multi-browser | Chromium, Firefox, WebKit out of box | Chromium + Firefox (WebKit experimental) |
| Multi-tab / multi-origin | First-class | Improving but historically limited |
| Parallelization | Built-in worker model | Cloud-only for free parallelism |
| Trace / debugging | Playwright Trace Viewer — excellent | Cypress Studio + time-travel |
| API testing | Built-in request fixture | Has it; less common pattern |
Trace Viewer — Your Flake Killer
Run with --trace=retain-on-failure and you get a single .zip per failed test that opens in the Trace Viewer: full DOM snapshots, network log, console, action timeline. Flakes that look like “the click missed” are usually quick to diagnose with the trace.
CI Setup That Stays Fast
- Shard across N workers in GitHub Actions matrix; merge HTML reports with
playwright merge-reports. - Cache the browser binaries — they're big.
- Only run cross-browser on PR or nightly; commits run chromium only.
- Block the merge on first-attempt pass; configure 1 retry on CI only for true cosmic-ray flakes; track retry rate.
# .github/workflows/e2e.yml
strategy:
fail-fast: false
matrix:
shardIndex: [1, 2, 3, 4]
shardTotal: [4]
steps:
- run: npx playwright install --with-deps chromium
- run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
- if: failure()
uses: actions/upload-artifact@v7
with:
name: trace-${{ matrix.shardIndex }} # artifact names can't contain a slash
path: test-results/Pitfalls
One mega-test per user journey
A test that signs up, configures, buys, and refunds in 90 steps is slow and unactionable when it breaks. Split by phase; share state via setup hooks, not by chaining.
Asserting on text that changes weekly
Marketing copy moves. Status messages get rewritten. Assert on roles, data-testids, URL changes, or stable substrings — not the full paragraph of welcome text.
Letting flake retries hide real bugs
Retrying flaky tests is fine; ignoring them isn't. Track flake rate per test; quarantine tests over a threshold and fix them. Otherwise the suite slowly becomes a coin toss.
Flakiness, Traces and Agents
A flaky E2E suite does more harm than having no suite at all, because people learn to ignore red. The usual causes are shared test data, timing assumptions and third-party services. Give each test its own data, created through an API rather than through the UI. Log in once with storageState, and reuse it. Mock third-party services, such as payment providers, at the network level with page.route.
Turn on tracing for failures. trace: 'retain-on-failure' gives you a full timeline, with DOM snapshots, network calls and console output, for any failed test. When a test fails in CI, you can step through it as if you'd been there, which is far better than a screenshot.
export default defineConfig({
retries: process.env.CI ? 2 : 0,
use: { trace: 'retain-on-failure' },
reporter: [['html'], ['github']],
});
Be careful with retries. They keep the build green while hiding a real race condition. Report flaky tests, and fix them. A retry is a temporary measure, and should never become a permanent one.
Coding agents and Playwright
Playwright has become a key tool for coding agents. Through its MCP server or CLI, an agent can open a real browser and use the app the way a person would. This closes a big gap, as Anthropic found when verifying long-running agents: results improved dramatically once the agent could test end to end, rather than just reading its own code.
Agents can also write tests. They're good at the first draft, and they need review. Generated tests often use brittle selectors, or assert what the page happens to show rather than what it should. Have them use getByRole and getByLabel, which match how users find things and survive redesigns. Those locators also keep your app accessible, because if a test can't find a button by its role, that's a useful warning that assistive technology may struggle too. It isn't a full accessibility audit.
Keep the suite small
E2E tests are the most expensive ones you own, so spend them on critical journeys: sign-up, checkout, and whatever makes you money. Cover everything else lower down. Fifty reliable tests beat five hundred that nobody trusts. Run a small smoke set on each pull request, and the full set after merge. Testing a Next.js or React app? Consider component tests for UI logic, which run far faster than a full browser journey.