Skip to content

Playwright Dos and Don'ts

Experienced Playwright teams converge on the same habits. This lesson lists concrete dos and don'ts you can pin in your repo README or PR template so new contributors avoid the mistakes that cause flaky suites.

Locator Dos and Don'ts

Do use getByRole('button', { name: 'Submit' }) and getByLabel('Email'). Don't rely on .class-name, #parent > div:nth-child(3), or XPath indexed paths that break when layout changes cosmetically.

Do add data-testid when no accessible role or label exists. Don't add test IDs to every element "just in case" — prefer roles first.

// DO
await page.getByRole('button', { name: 'Checkout' }).click();

// DON'T
await page.locator('.btn.btn-primary.checkout-v2').click();

Role locators survive CSS refactors that don't affect semantics.

Waiting Dos and Don'ts

// DO: wait for condition
await expect(page.getByText('Success')).toBeVisible();

// DON'T: arbitrary sleep
await page.waitForTimeout(3000);
  • Do await every Playwright API call.
  • Don't share logged-in state by running tests in order without isolation.
  • Do mock APIs with page.route() in UI tests.
  • Don't commit test.only or page.pause() to main.

Dos and Don'ts Table

At-a-glance habits.

Do Don't
getByRole / getByLabel Brittle CSS chains
expect() auto-retry waitForTimeout()
storageState for auth UI login in every test
page.route() stubs Prod API in CI
Trace on failure Ignore CI artifacts
Fresh context per test Serial dependent tests
Tag @smoke tests Run full suite on every save

CI Dos and Don'ts

Do cache browsers, use --with-deps, health-check the app, upload reports on failure. Don't use fixed sleeps for app startup or run unlimited workers on 2GB CI runners.

Debugging Dos and Don'ts

Do use UI Mode and Trace Viewer locally. Don't leave slowMo or pause() in committed code. Do share trace zips when asking for help — don't paste only the Node stack trace.

Common Mistakes

  • Treating this list as optional — each "don't" exists because teams hit it repeatedly.
  • Enforcing dos only in code review, not in lint rules or CI guards.
  • Applying Selenium explicit-wait habits to Playwright.
  • Adding don'ts without teaching the corresponding do in onboarding.

Key Takeaways

  • Prefer accessible locators and expect() over CSS and fixed sleeps.
  • Mock network and reuse auth for speed and stability.
  • Treat CI artifacts and test isolation as non-negotiable.
  • Pin this list where contributors will see it before opening a PR.

Pro Tip

Convert your top three recurring review comments into automated checks — saves the same feedback every PR.