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
IDs
on the same page - But this should also apply to the 'data-cy' or 'data-test-id' attributes. - When
IDs
are 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.
id
attribute of html element should not really be used, because at least earlier there was a requirement thatid
attribute must be unique so having multiple components of same type would need to have differentid
's withdata-
attributes there is no such problem... – Ceratoid