How to Write Stable Locators
|
|
Strategy
When you are thinking about locators you need to think about your goal. The goal is usually to make them “stable”. So, then you need to think about what “stable” means.
You want to make sure that your tests won’t break when rendering changes. What does “rendering change” mean? The HTML structure, order of elements, names of elements, and how these things are rendered on the page and to the end user.
So, how do we make a test stable in this situation?
We need to refer to elements in a way that is guaranteed to work in all of the situations of the above changes. How?
Manual Testing for Toddlers
You should think about automation as giving instructions to a 5-year-old child who is doing manual testing and not familiar with your app or any of the concepts that you know about testing or your industry.
The best way to refer to elements is to make it easy for that child to find them even if your UI changes.
Let’s consider this screenshot:

Followed by

- HTML structure will likely change very soon.
- Labels outside their respective inputs (like “First Name” and “Last Name” in the image) might become greyed out placeholders inside the input.
- The order of elements may change.
What is the way to address it?
Create a meaningful reference that uniquely identifies the element and is generic enough to survive future changes.
enter “Peter” into “First Name” or “First” in the section “Billing Address”
- We provided alternative options to refer to the element “First” if “First Name” is not found.
- We provided a reference to the section to make sure we differentiate between billing and shipping addresses.
- It will find the “Billing Address” section first.
- Then, in that section, it will find the element by description, regardless of whether it is something that looks like a label or placeholder.
- Avoid referring to the element by locators that are not visible by the end user (e.g., ids). Since they have a tendency to change with UI framework updates/changes and will break your tests when they are not found.
- Avoid making references to elements that are not descriptive and rely on positioning of your UI elements. You should never rely on the “First Name” input by using
enter “Peter” into the first input above the “City”, since this would make it rely too heavily on specifics of the rendering.
What to do if there are no good solutions?
Sometimes there are no good, clean solutions like in the picture above. What do you do in this case?
- Identify logical anchors for the element. What would be its section or area or something else this element belongs to.
- If there is absolutely nothing, try to find the anchor most likely to stay in the position relative to the element.
- Prefer anchors that are above or on the left of the element.



