Playwright Best Practices
Use this for browser-level tests that should behave like a reliable user.
Project Fit Check
Before writing tests:
- Read existing Playwright config, fixtures, helpers, test ids, auth setup, route mocks, and CI commands.
- Follow the repo's locator strategy.
- Reuse existing page objects/helpers only when they reduce duplication.
- Keep assertions tied to user-visible behavior and accessibility semantics.
- Do not add sleeps to hide race conditions.
Test Rules
- Prefer role, label, text, and stable test ids over CSS selectors.
- Assert the outcome, not every implementation step.
- Keep tests isolated and repeatable.
- Use fixtures for auth and shared setup.
- Mock external services at the boundary when real services make tests slow or flaky.
- Keep mobile/responsive tests explicit when layout or touch behavior matters.
Debugging Flow
- Reproduce with the smallest test command.
- Inspect trace, screenshot, console, and network output.
- Identify whether the failure is product bug, selector drift, async race, data setup, browser difference, or environment issue.
- Fix the cause, not the timeout.
- Re-run the failed test and any nearby coverage.
Locator Rules
- Use
getByRolewhen semantics are stable and meaningful. - Use
getByLabelfor form controls. - Use project test ids for complex widgets or localized copy.
- Avoid nth-child selectors unless testing ordered content explicitly.
Red Flags
waitForTimeout- broad CSS selectors
- tests depend on run order
- production third-party service required for normal CI
- assertion passes before async work completes
- UI changed but accessibility name no longer matches intent