One of the top frustrations in test automation is flaky tests — tests that fail sometimes, pass other times, even when nothing changed.
👉 Most of the time, the culprit is a bad locator strategy.
In this guide, I’ll show you how to pick locators that actually reduce flakiness, with real-world examples and templates you can reuse.
❌ Why Flaky Tests Happen
- Using fragile locators like XPath with long indexes (
/div[2]/table/tr[3]/td[5]) - Relying on text or attributes that change often
- Dynamic IDs or auto-generated selectors
- No synchronization → the test checks before the element is ready
✅ Principles of a Stable Locator Strategy
- Prefer unique IDs or data-test attributes
- Example:
id="login-button"ordata-test="checkout-btn" - Add these attributes in dev code if they don’t exist → QA + Dev collaboration.
- Example:
- Use semantic, stable selectors
- Prefer
button[type='submit']overdiv > div > span > button[2].
- Prefer
- Avoid dynamic attributes
- Bad:
id="user_1243"(number changes every session). - Instead:
id^="user_"(starts-with selector) or a stable sibling element.
- Bad:
- Fallback with hierarchy only when necessary
- Use relative paths anchored to stable elements:
- Example:
//form[@id='login-form']//input[@name='username'].
- Wait properly
- Always combine locators with explicit waits (Playwright auto-wait, Selenium
WebDriverWait).
- Always combine locators with explicit waits (Playwright auto-wait, Selenium
🧩 Example: Login Button
- ❌ Fragile XPath:
//*[@id="root"]/div/div[2]/form/div[3]/button[1] - ✅ Stable locator:
data-test="login-btn"orbutton[type='submit']
👉 Result: 95% fewer false failures when page structure shifts.
🛠️ Tools & Practices That Help
- Playwright → auto-waits for elements to be ready.
- Selenium → combine with
WebDriverWaitto handle async loads. - Page Object Model (POM) → centralize locators in one place so fixes are easier.
- Static data-test attributes → add them in the app codebase whenever possible.
📚 Templates to Use
To save time, I’ve included Locator Strategy Checklists inside the Free QA Kit:
- ✅ Do’s and Don’ts for locators
- ✅ Sample Page Object Model (POM) locator file
- ✅ Examples in Selenium + Playwright
🎯 Final Takeaway
Flaky tests aren’t “just part of automation.” Most of the time, they’re a locator problem.
By sticking to stable, semantic, and agreed-upon locators, you’ll:
- Cut down flaky failures
- Save hours of re-runs
- Build trust in your automation suite
🚀 Next Step: Review your current test suite → replace fragile XPath with stable attributes → watch your flakiness rate drop.


Leave a Reply