Skip to main content

Locator strategy

Choosing the right locator strategy is crucial for building reliable and maintainable end-to-end tests. This section outlines the recommended locator strategies, ordered by priority and aligned with best practices, to ensure your tests remain robust and expressive as your application evolves.

  • Using data-testid (or any dedicated test attribute) as the primary locator strategy makes the tests more stable, easier to maintain and focused on test behavior rather that UI structure.
  • Playwright encourages using semantic, resilient selectors that mirror how users interact with the UI, rather than relying on fragile or implementation-specific details like CSS classes or XPath.

In order of priority:

  1. data-testid attributes (getByTestId)
  2. User-facing attributes recommended by Playwright:
    1. getByRole
    2. getByText
    3. getByLabel
    4. getByPlaceholder
    5. getByAltText
    6. getByTitle
  3. Other locators (page.locator)