Locator
// Definition
A description of how to find an element on a page — by id, CSS, XPath, role, or test attribute. Modern frameworks prefer role and test-id locators because they're resilient to DOM changes.
// Why it matters
A locator is how a test finds an element, and it's the single biggest determinant of suite stability. Brittle locators (deep CSS, nth-child, XPath tied to layout) break on every redesign; resilient ones (role, test-id, accessible name) survive. QA that invests in locator strategy spends far less on maintenance.
// How to test
// Prefer stable, intent-revealing locators over structural ones
// ❌ brittle — breaks if the markup shifts
cy.get('div.container > ul > li:nth-child(3) > button')
// ✅ stable — survives restyling
cy.get('[data-cy=add-to-cart]')
cy.findByRole('button', { name: /add to cart/i }) // also asserts accessibility// Code Example
// Prefer role and accessible name — survives styling changes
await page.getByRole('button', { name: 'Sign in' }).click();
await page.getByLabel('Email').fill('user@example.com');
// Test-id when no semantic option fits
await page.getByTestId('user-menu').click();
// CSS — quick but brittle
await page.locator('.nav-cta').click();// Common mistakes
- Locating by text that's user-facing copy (breaks on every wording tweak)
- Chaining long CSS paths that encode the current DOM structure
- Using auto-generated class names (hashed CSS-module names) as hooks
// Related terms
Selector
A CSS or XPath expression that identifies one or more DOM elements. Often used interchangeably with 'locator', though locator is the broader concept.
Assertion
A statement in a test that checks an expected condition holds. If it doesn't, the test fails. The core of every automated test.
Auto-waiting
A framework feature that pauses an action until the target element is actionable (visible, enabled, stable). Eliminates most need for explicit sleeps and reduces flake.
Learn more · JavaScript for QA
Chapter 6 · Lesson 2: Selecting Elements — querySelector and getElementById