Cypress · Browser testing end to end

Why use data-cy attributes for testing?

Easydata-cyselectorstestabilityUpdated Oct 2026
Quiz this track

Short answer

data-cy attributes are explicit, stable hooks for tests. They do not depend on styling or DOM structure, they are easy to search in the codebase, and they make the test contract obvious to developers.

A data-cy attribute is a deliberate test hook. It says that this element is a meaningful target, independent of how it looks. A class can change with a design token rename; a data-cy name changes only when the product intent changes, which is exactly when the test should change too.

tsx
export function SaveButton({ onSave }: { onSave: () => void }) {
  return (
    <button data-cy="save-profile" onClick={onSave}>
      Save profile
    </button>
  );
}
The attribute lives with the component, so the selector is discoverable by searching the source.

How to use them well

  • Name by purpose, such as save-profile or cart-item, not by position
  • Keep one attribute per meaningful element rather than decorating everything
  • Scope shared names with a container, such as cart-item plus remove
  • Prefer a consistent convention so the team can grep for data-cy
  • Do not expose secrets or user data in attribute values

Some teams prefer data-testid or data-test. The exact name matters less than consistency because Cypress can query any attribute. Pick one and document it so tests do not mix three conventions.

data-cy is not a substitute for accessible markup. A button should still have a label and real semantics; the attribute only makes it easier for the test to find that button.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How would you handle a list of dynamically generated items?
  2. 2Should every element have a data-cy attribute?
  3. 3What is the difference between data-cy and data-testid?
  4. 4Can data-cy attributes affect production behaviour?

Say it in the interview

I use data-cy as a stable, intentional hook for tests. It does not depend on styling or DOM position, and searching the source for the attribute shows exactly where the test target lives. I name attributes by purpose and scope repeated ones with a container. I still keep the markup accessible; the attribute is a convenience for the test, not a replacement for semantics.

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.