Cypress and many other posts around testing web applications suggest relying on a data attribute like data-cy
or data-test-id
for locating elements rather than relying on the id
attribute.
My understanding is that for two reasons:
IDs
on the same page - But this should also apply to the 'data-cy' or 'data-test-id' attributes.IDs
are tied to CSS
, there's a tendency to change them more often while data-*
attributes may be less prone to change.Can someone please throw more light on the recommendation?
The other thing I am considering is to request my devs to place the data-test*
attributes on a div
tag that would consume the component - that way the test attribute is actually one level above the component id
attribute and may come handy even in cases where multiple instances of the same component are used. But again, I am not sure why the id
attribute for that div
tag is bad when compared to the data-test*
attribute.
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
No. That would be invalid - HTML does not allow < or > inside attributes.
data-testid is an attribute used to identify a DOM node for testing purposes. It should be used as a handler to the test code. We need to make sure its value is unique. Therefore, we do not cause conflicts between components.
From Cypress official docs:
Anti-Pattern: Using highly brittle selectors that are subject to change.
Best Practice: Use data-* attributes to provide context to your selectors and isolate them from CSS or JS changes.
Every test you write will include selectors for elements. To save yourself a lot of headaches, you should write selectors that are resilient to changes.
Oftentimes we see users run into problems targeting their elements because:
Your application may use dynamic classes or ID's that change Your selectors break from development changes to CSS styles or JS behavior Luckily, it is possible to avoid both of these problems.
Don't target elements based on CSS attributes such as: id, class, tag Don't target elements that may change their textContent Add data-* attributes to make it easier to target elements
The point is that id's and classes can be dynamic (also text-content) so you always want to use a selector that is static like the "data-cy" attribute.
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