I’m new to Cypress automation testing and noticed that Cypress best practices recommend using a Cypress test id like data-cy or data-test-id for selecting elements. My question is:
Where exactly should I add the data-cy or data-test-id attribute to an element I want to test?
Should I:
a) Check out the source code from the dev team and add the attribute there?
b) Use Cypress’s invoke command to add it dynamically during tests?
c) Use some other method?
If option (a) is correct, how do you usually approach this? Should the app and test code live in the same repo? And what’s the best way to structure selectors for maintainability?
For context: my frontend is built in TypeScript + React, backend is in SQL, and tests are written in Cypress in a separate project.
I’ve been working with Cypress for a bit now, and I’d say the best place to add a cypress test id is right in the component itself. It gives you a stable target to select during tests and avoids coupling your test logic with CSS classes or layout structure. It’s a simple habit that really pays off when tests start to grow.
Totally agree, @madhurima_sil. I’ve also played around with injecting the cypress test id dynamically using .invoke()
, especially when working on prototypes. But that approach can get flaky fast—React re-renders wipe out those changes, and selectors break. What stuck with me was how reliable things became once we added those attributes directly in the codebase. It’s CI-friendly and removes a lot of guesswork from the test layer.
Right there with you, @panchal_archanaa. I’ve seen the most consistency when cypress test id attributes are baked into the component from the start. In our team, we’ve made it a standard to add them during component development, no impact on the UI, but a big win for test stability. Plus, using clear naming conventions like data-cy="submit-btn"
helps when scaling. Oh, and separating test code into its own repo? Totally works, as long as the dev and QA teams stay in sync.