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:
- The modern way of re-using the components can lead to having multiple components of the same type and can lead to multiple of those
IDson the same page - But this should also apply to the 'data-cy' or 'data-test-id' attributes. - When
IDsare tied toCSS, there's a tendency to change them more often whiledata-*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.