Skip to content

Chapter 2 of 8

Selectors, Locators, and Resilient Tests

The single biggest source of flaky Playwright tests is bad selectors, so the framework steers you toward accessibility-driven queries. getByRole, getByLabel, getByPlaceholder, and getByText let you describe elements the way a user or screen reader would, which makes tests resilient to DOM refactors and visual redesigns. When semantics genuinely aren't available, such as unlabeled icon buttons or volatile i18n text, the escape hatch is a stable data-testid attribute added in a way that doesn't tie tests to copy or layout. You can rename the attribute globally through testIdAttribute in the config.

A Locator is more than a CSS string: it's a live handle that re-resolves on every action and participates in Playwright's strict mode. Most locator actions throw if more than one element matches, which forces you to disambiguate up front. Common disambiguation patterns include narrowing with .filter({ hasText } or { has: page.getByRole(...) }), scoping with a parent locator like a card or row, or as a last resort using .nth(i). The same scoping idea works inside iframes through frameLocator, where you call getByRole or getByTestId against the frame rather than the top page.

When the UI changes a lot, snapshotting accessibility trees with page.accessibility.snapshot() and asserting on role/name pairs catches a11y regressions in addition to functional ones. Combined with prefers-reduced-motion, disabled animations, fixed viewports, and consistent fonts, this strategy keeps visual tests stable. Where multiple similar elements exist, e.g. rows that share a button, scope the locator to its container first, then run getByRole inside that scope. This habit prevents the dreaded 'strict mode violation' errors that show up the moment a list grows by one row.

All chapters
  1. 1Foundations: Installing and Configuring Playwright
  2. 2Selectors, Locators, and Resilient Tests
  3. 3Assertions, Waits, and Avoiding Flakiness
  4. 4Running, Tagging, and Debugging Tests
  5. 5Authentication, State, and Data Isolation
  6. 6Visual Regression and Snapshots
  7. 7CI/CD, Reports, and Parallel Execution
  8. 8Workspace Workflows and AI Agent Collaboration

Drill it

Reading is not remembering. These come from the Anki Playwright Agents deck:

Q

Playwright (Node): minimal setup?

npm i -D @playwright/testnpx playwright installnpx playwright test

Q

Where do Playwright tests live?

Common: ./tests or ./e2e (you choose). Configure testDir in playwright.config.ts so agents know where to add new tests.

Q

Key playwright.config.ts settings?

use.baseURL, webServer (start app), projects (chromium/firefox/webkit), retries/workers, reporter (html + junit), trace/video/screenshot policies.

Q

How do I auto-start my app for tests?

Use playwright.config.ts webServer: { command: "npm run dev", url: "http://127.0.0.1:3000", reuseExistingServer: !process.env.CI }.