When writing tests, prioritize semantic and accessibility-based selectors over data attributes or generic selectors. Use accessible names, roles, and text content to select elements, as these selectors validate both functionality and accessibility simultaneously.
When writing tests, prioritize semantic and accessibility-based selectors over data attributes or generic selectors. Use accessible names, roles, and text content to select elements, as these selectors validate both functionality and accessibility simultaneously.
Preferred approach:
// Good - validates both functionality and accessibility
cy.contains('button', 'Choose Editor').click()
cy.findByRole('button', { name: 'Save Settings' }).click()
// Acceptable when semantic selectors aren't sufficient
cy.get('[data-cy="choose-editor"]').click()
// Avoid - fragile and doesn't validate accessibility
cy.get('.btn-primary').click()
cy.get('button').first().click()
Key benefits:
When to use data selectors:
Ensure your tests validate meaningful behavior rather than just element presence. A test that only checks if a component renders without validating its actual functionality provides limited value and may give false confidence.
Enter the URL of a public GitHub repository