5. Selectors, the DOM, and stable locators
Test Automation · 48 pages source format
Flaky tests often start with brittle locators. Learn to read the DOM, prefer roles and test IDs, and treat selectors as product contracts — before you depend on any framework.
What you'll learn
- DOM basics for testers
- Role / label / test-id hierarchy
- Why XPath spaghetti dies
Tour DevTools
Elements, Console, Network. You will live here. Practice selecting nodes and reading accessibility names.
Do this now
Open any form. Find the accessible name of the submit button in DevTools Accessibility pane.
Locator preference order
Prefer getByRole / label text → test id → CSS → XPath last. User-facing queries survive redesigns better.
Do this now
Rewrite three CSS selectors as role or test-id queries on paper.
Pro tip. Ask eng for data-testid on critical controls — it is a feature, not a cheat.
Assert outcomes, not pixels
Assert URL, text, enabled state, API response — not “div.x is red” unless visual risk is the point.
Do this now
For a login success, write 2 good asserts and 1 bad assert. Explain why the bad one is brittle.
Selector policy doc
Teams that survive have a written locator standard. One page beats tribal knowledge.
Do this now
Draft SELECTORS.md: preference order, banned patterns, when to request test ids from dev.