I read following in cypress's best practices.
Anti-Pattern: Using highly brittle selectors that are subject to change.
Best Practice: Usedata-*
attributes to provide context to your selectors and isolate them from CSS or JS changes.
But I also came across following points:
The reason using the actual text/role is better is because that's what the user sees and how they know to navigate the app. e.g. the user clicks the "Home" button. If you rename "Home" to "Dashboard" then the user will have friction, not knowing where their "Home" button went, and so it's OK for that same friction to appear in the test, because the test is supposed to capture the breaking change from the user's perspective
data-cy
sounds like binding UI tests to implementation detail, rather than actual content and behavior. Theoretically, the only time your UI tests should have to change is when content or behavior changes.The id attribute is made to be unique. So why not use it?
The argument in favor of data-cy
is:
data-cy
gives developers sense that they shouldn't touch their value unnecessarily. The values may be made to simply duplicate something describing content or behavior. Now, developers may think of changingdata-cy
values only when content or behavior changes. So, at least DOM restructuring or change in CSS wont break the tests (if they were written using DOM or CSS based element selectors). To tightly binddata-cy
to content or behavior, we may opt to programmatically set to something capturing content or behavior, so that they wont be left unchanged if content or behavior changes.
But I dont know how much this argument fair against the earlier ones. What is correct among these?