Locator strategy & waiting discipline

Role/test-id locators over brittle CSS/XPath; explicit conditions over sleeps. 80% of flaky UI tests are a waiting-strategy bug.

About 20 min read3-question knowledge check

The mental model

A locator is an address, and a wait is a promise about time. Get either wrong and the test is a coin flip. The whole discipline of stable UI automation reduces to two questions asked before every action: how do I name this element so it survives change? and what condition proves the app is ready for me to act?

The analogy that sticks: locating an element is like **addressing a letter**. A brittle CSS/XPath selector — div.container > ul > li:nth-child(3) > button.btn-primary — is a set of turn-by-turn directions ("third house past the oak tree"): correct today, wrong the day someone plants a hedge. A role or test-id locator — getByRole('button', { name: 'Delete' }) or getByTestId('delete-account') — is a named recipient: the letter reaches them even if they move house, because you addressed who they are, not where they stood.

Waiting is the other half, and the industry's hardest-won lesson lives here: **sleep(n) is a bet that the app will be ready in exactly n milliseconds, every time, on every machine.** It never is. A CI runner under load, a cold cache, a slow network — any of these makes n too short and the test flakes; pad n to be safe and every run pays the tax. The professional replaces the *guess about time* with an *assertion about state*: wait until the button is enabled, until the row appears, until the spinner is gone. Most flaky UI tests trace back to waiting problems, because a selector that matches nothing usually fails loudly, while a bad wait fails intermittently — which is far more expensive to diagnose.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision