问题
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 same type and can lead to multiple of those Ids in the same page - But this should also apply to the 'data-cy' or 'data-test-id' attributes
- When Ids are tied to CSS, there is 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's 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 id attribute for that div tag is bad when compare the data-test* attribute.
来源:https://stackoverflow.com/questions/58794288/when-developing-e2e-tests-why-is-data-attributes-preferred-for-element-select