I'm currently placing some ID's on elements for UI Test automation. These ID's are only being used for testing. Should I be adding data-attributes instead possibly making it more readable to future developers(data-testHandle="mybutton") or should I stick with ID's.
w3.org says:
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
I'm leaning towards keeping ids but some part of me thinks that future developers would think the ID's aren't used and remove them.
Any best practices here. Thanks.
Published Jun 5, 2022. + Follow. A CSS selector is a string that is designed to locate one or more elements on a webpage, specifying attributes and/or hierarchy (parent in the DOM) of the elements. CSS Selectors are one of the locators that can be used to find elements while writing automation scripts.
An element is an HTML element from the page such as an input field or an anchor. We can then do actions on the element in order to automate the behaviour we are trying to implement, such as clicking and populating fields. Fortunately for us, Selenium provide us with many methods to find elements.
Solution: Data-qa AttributesThese HTML attributes enable us to create custom attributes on every HTML element. So the solution is to create 'data-QA' attributes for HTML elements. These attributes can be only used for the UI automated test and don't interfere with any functions or purposes on the page.
This is close to being opinion-based, by here is the summary that should help to make a choice.
Why would you use an ID
attribute:
document.getElementById()
which is optimized by the modern browsers (though, usually performance of the end-to-end UI tests is not critical)id
s of the element whenever possible #myid .someclass
as opposed to [automation-id=myid] .someclass
.Why would you use a custom attribute:
automation-id
attributes to all the desired elements, you would somewhat namespace/scope it to the test automation - everybody would know what is this for just from the attribute name. Meaning, you would dramatically decrease chances of a developer changing the attribute intentionally as opposed to an id
attribute, which can and is usually used for application client-side logic as well (reference to this and this answer)Also, here are some relevant threads:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With