Course contentsShow
← Software Engineering
Lesson 563 of 1,93317. End-to-End and UI TestingFree lesson

Locator Strategies and Best Practices

Choosing resilient selectors (test IDs, ARIA labels) over fragile ones (CSS classes, XPath) for stable tests.

Locator Strategies and Best Practices

What you'll learn: How to select UI elements in your end-to-end tests using strategies that keep tests stable when the UI changes.

Why Locator Strategy Matters

When writing E2E tests with the Page Object Pattern, you need to tell your testing tool how to find buttons, input fields, and other elements on the page. This is called a locator. The problem? Not all locators are equally reliable.

Fragile vs Resilient Locators

Think of locators like addresses. Would you rather give someone directions using "the blue house" (which becomes wrong after a paint job) or "123 Main Street" (which stays stable)?

Fragile locators break easily when developers change styling or layout:

  • CSS classes: button.btn-primary.submit-style – classes change for styling reasons
  • Complex XPath: /html/body/div[3]/form/div[2]/button – breaks if structure shifts

Resilient locators survive UI refactoring:

  • Test IDs: data-testid="submit-button" – explicitly added for testing
  • ARIA labels: role="button" aria-label="Submit form" – semantic and accessibility-friendly
  • Semantic HTML: <button name="submit"> – uses meaningful attributes

Best Practices

  1. Prefer test-specific attributes like data-testid – they signal testing intent to developers
  2. Use ARIA labels when available – improves accessibility and test stability
  3. Avoid implementation details like CSS classes designed for styling
  4. Keep selectors simple – shorter selectors are easier to maintain

When UI developers know an element has a data-testid, they'll preserve it during refactoring. But they'll freely change .btn-blue to .btn-primary without realizing tests depend on it.

Key Takeaway: Choose locators based on semantic meaning and testing intent, not styling or DOM structure, to build E2E tests that survive UI changes.