Skip to content

Best Locators

Stable locators are the foundation of maintainable E2E tests. This lesson summarizes Playwright's recommended priority and team practices.

Locator Priority Order

Playwright docs recommend: getByRolegetByLabelgetByPlaceholdergetByTextgetByAltTextgetByTitlegetByTestId → CSS/XPath last.

Work with developers to add data-testid only where semantic locators fail — custom widgets, canvas, third-party embeds.

// Best
page.getByRole('button', { name: 'Checkout' })

// Good when role ambiguous
page.getByTestId('checkout-btn')

// Avoid in new tests
page.locator('div.container > ul li:nth-child(3) a')

If your locator reads like a DOM path, reconsider.

Team Conventions

// playwright.config.ts
use: { testIdAttribute: 'data-test-id' }

// In app markup
<button data-test-id="submit-order">Submit</button>
  • Agree on one test id attribute name across app and config.
  • Document locator standards in CONTRIBUTING.md.
  • Reject PRs that add CSS-class-only hooks for tests.
  • Review codegen output — edit toward role locators before committing.

Locator Decision Tree

Pick the right locator in seconds.

Question Choose
Has accessible role+name? getByRole
Labeled form field? getByLabel
Only placeholder visible? getByPlaceholder
Static text block? getByText
Image? getByAltText
Legacy/custom component? getByTestId
Nothing else works? Scoped CSS, then ask devs for test id

Collaborating with Developers

  • Add test ids during feature work, not after flaky tests appear.
  • Use semantic HTML so roles come free.
  • Avoid reusing test ids on repeated list items — include dynamic suffix or scope by row.

Linting and Review Checklist

During code review, flag XPath, deep nth-child chains, and text copied from marketing. Encourage toHaveRole debug when locators fail.

Common Mistakes

  • Copying selectors from Chrome DevTools right-click copy.
  • Different test id conventions in app vs config attribute name.
  • Testing implementation details (CSS modules hashed class names).
  • Overusing test ids when a role locator would test accessibility too.

Key Takeaways

  • Follow role-first locator priority from official docs.
  • Test ids are a contract — use consistently, not as first resort.
  • Brittle CSS/XPath creates maintenance debt.
  • Good locators improve both test stability and a11y.

Pro Tip

Add a custom ESLint rule or grep CI check that fails on page.locator('// XPath in spec files.