Back To Blogs

Test Locator Strategy: Selectors That Survive Redesigns

When a UI test breaks after a harmless design change, the locator is almost always to blame. A good locator strategy makes tests resilient, readable and, as a bonus, encourages an accessible UI.

The principle: locate elements the way users find them

Users don't see div.sc-1x2y3 > span:nth-child(4). They see "the Add to cart button" or "the Email field". Tests that locate by the same cues break only when the user experience changes, which is exactly when they should break.

A priority order

  1. Role + accessible name: getByRole('button', { name: 'Place order' })
  2. Label: getByLabel('Email address') for form fields
  3. Visible text: getByText('Your cart is empty') for non-interactive content
  4. Placeholder, alt text, title: when nothing better exists
  5. Test ID: getByTestId('cart-total') for elements with no stable user-facing cue
  6. CSS: short, stable selectors only (#checkout-form), as a last resort
  7. XPath: avoid, except for rare structural cases

Playwright's recommended locators follow essentially this order; with Cypress, Testing Library's findByRole and findByLabelText give you the same approach.

Examples

// ✅
await page.getByRole('button', { name: 'Apply coupon' }).click();
await page.getByRole('link', { name: 'Order history' }).click();

// ❌
await page.click('.btn.btn-primary.mt-2');
await page.click('//div[3]/a[2]');

Form fields

await page.getByLabel('Email').fill('[email protected]');
await page.getByLabel('Number of guests').fill('7');

If getByLabel can't find the field, the field probably has no proper label, which is an accessibility bug worth reporting.

Scoping inside lists and tables

const tshirtRow = page.getByRole('listitem').filter({ hasText: 'T-shirt' });
await tshirtRow.getByRole('button', { name: 'Remove' }).click();

Filtering by content beats positional selectors like nth(2), which break as soon as the order changes.

Values with no user-facing label

<span data-testid="cart-total">$12.00</span>
await expect(page.getByTestId('cart-total')).toHaveText('$12.00');

Agree on a test ID convention with developers (data-testid, kebab-case, named by meaning rather than position).

Anti-patterns

  • Generated class names (.css-1q2w3e) change on every build
  • Deep CSS chains encode layout that designers will change
  • Index-based selection (.product:nth-child(3)) breaks when data changes
  • Text with dynamic values, e.g. getByText('Total: $37.00'), when the value is what you're asserting; locate the element, then assert its text
  • Locators that match several elements: Playwright's strict mode will flag this; fix it rather than taking .first() by habit

Working with developers

  • Ask for semantic HTML: real <button> and <a> elements, <label for> on inputs
  • Agree where test IDs are appropriate
  • Treat "I couldn't locate this by role or label" as an accessibility signal, not just a testing nuisance

Tooling that helps

  • Playwright codegen and the Pick locator tool in UI mode suggest role-based locators
  • Chrome DevTools → Accessibility pane shows each element's role and accessible name
  • Testing Library queries bring the same discipline to Cypress and component tests

Locator review checklist

  • Would this locator survive a CSS redesign?
  • Would it survive a change in item order?
  • Does it match exactly one element?
  • Does it read like a user instruction?

Practise on realistic apps

The apps in QAUnlocked Practice Labs use semantic buttons, labelled form fields and stable test hooks, so they're a good playground for writing locators the right way. Find the bugs manually first, then automate the checks with role-based locators. Then quiz yourself on automation concepts in a battle.

locatorsselectorsplaywrightcypresstest automation

Comments

0 Comments

Be the first to comment.