In Cypress tests, why is it best to use data-* attributes as selectors instead of classes or IDs?
Think about what changes often in UI and what stays stable for testing.
Using data-* attributes keeps selectors stable because they are meant for testing and do not change with styling or layout updates.
Given a button with HTML: <button data-test='submit-btn' class='btn primary'>Submit</button>, which Cypress selector is best for stable tests?
Look for the selector that is least likely to break if styles or text change.
Using data-test attribute is stable and independent of styling or text changes, making tests less brittle.
Consider this Cypress test code snippet:
cy.get('[data-cy=login]').click()
cy.get('.btn-primary').should('be.visible')If the data-cy attribute is missing but the class exists, what happens?
Think about what happens if a selector targets a missing attribute.
The first cy.get fails because the element with data-cy=login does not exist. The second command passes if the class .btn-primary is present and visible.
Review this Cypress selector code:
cy.get('button.submit-btn.active').click()The test intermittently fails because the button is not found. What is the likely cause?
Consider how class combinations affect element matching.
The selector looks for a button with both classes submit-btn and active. If the active class is added dynamically, the selector may fail when the class is missing.
Choose the selector strategy that best supports maintainable and robust Cypress tests in a large project.
Think about what makes selectors stable and easy to maintain as UI changes.
Using unique data-cy attributes isolates selectors from styling and layout changes, making tests more maintainable and less brittle.