Using data-cy attributes helps keep tests stable and easy to maintain. They act like special name tags for elements that tests can find reliably.
0
0
data-cy attributes for test stability in Cypress
Introduction
When you want your test to find a button or input without breaking if the design changes.
When CSS classes or IDs change often but you want your tests to keep working.
When you want to separate test selectors from styling or functionality code.
When you need clear, simple ways to identify elements in your test scripts.
When working with a team to make tests easier to understand and update.
Syntax
Cypress
<element data-cy="unique-name">...</element> // In Cypress test: cy.get('[data-cy="unique-name"]')
The data-cy attribute is a custom HTML attribute used only for testing.
Use unique and descriptive names for data-cy values to avoid confusion.
Examples
This example shows a button with a
data-cy attribute and how to click it in a test.Cypress
<button data-cy="submit-button">Submit</button> // Cypress test cy.get('[data-cy="submit-button"]').click()
Here, an input field is selected by
data-cy and text is typed into it.Cypress
<input data-cy="email-input" type="email" /> // Cypress test cy.get('[data-cy="email-input"]').type('user@example.com')
This example checks that the user profile section contains the name 'John'.
Cypress
<div data-cy="user-profile"> <p>Name: John</p> </div> // Cypress test cy.get('[data-cy="user-profile"]').should('contain', 'John')
Sample Program
This test visits a page, clicks the login button identified by data-cy, and checks if the URL changes to include '/dashboard'.
Cypress
// HTML snippet <button data-cy="login-button">Log In</button> // Cypress test describe('Login Button Test', () => { it('clicks the login button', () => { cy.visit('https://example.com') cy.get('[data-cy="login-button"]').click() cy.url().should('include', '/dashboard') }) })
OutputSuccess
Important Notes
Do not use data-cy values that might change often, like user names or dynamic content.
Keep data-cy attributes only for testing to avoid mixing test code with app logic.
Using data-cy makes tests less fragile compared to using classes or IDs that change with design.
Summary
data-cy attributes help tests find elements reliably.
They keep tests stable even if the page design changes.
Use clear, unique names for easy test maintenance.