Cypress · Browser testing end to end
How should you choose selectors in Cypress?
Short answer
Prefer stable attributes such as data-cy, then accessible roles or labels, and avoid CSS tied to layout or styling. Good selectors survive refactors because they describe intent, not presentation.
A selector is a contract between the test and the application. If the contract is a styling class or a DOM position, a redesign breaks the test even when behaviour is unchanged. If the contract is a purpose-built attribute or an accessible name, the test follows the product.
cy.get("[data-cy=checkout-button]").click();
cy.get("[data-cy=cart-item]")
.filter(":contains('Wireless keyboard')")
.find("[data-cy=remove]")
.click();A practical order
- data-cy or another dedicated test attribute for controls you own
- Accessible role, label or visible text when it matches how users find the element
- Stable domain attributes such as name or aria-label
- Avoid auto-generated class names, nth-child and long CSS paths
- Scope with .within or .find instead of writing one enormous selector
For repeated elements, select the collection and filter or use .eq with a stable identifier. Avoid relying on order when the order is not part of the behaviour. If the list is genuinely ordered, assert the order explicitly rather than using it silently as a locator.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why are data-cy attributes better than CSS classes?
- 2How do you select the third row of a table safely?
- 3When would you use cy.contains instead of cy.get?
- 4How does .within help with large pages?
Say it in the interview
I choose selectors that describe intent. data-cy attributes are my default for controls I own, and I fall back to accessible names or visible text when that matches the user's view. I avoid styling classes, nth-child and long CSS paths because they break on refactors without a behaviour change. For repeated elements I scope with within or find and filter by a stable value.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Cypress mock interview and get scored feedback on depth, clarity and confidence.