0
0
Cypresstesting~15 mins

data-cy attributes for test stability in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify login functionality using data-cy attributes
Preconditions (4)
Step 1: Enter 'user@example.com' in the email input field identified by data-cy='email-input'
Step 2: Enter 'Password123!' in the password input field identified by data-cy='password-input'
Step 3: Click the login button identified by data-cy='login-button'
Step 4: Wait for the page to navigate to the dashboard
✅ Expected Result: User is redirected to the dashboard page with URL containing '/dashboard'
Automation Requirements - Cypress
Assertions Needed:
Verify the URL contains '/dashboard' after login
Verify the login button is clickable
Verify input fields accept text
Best Practices:
Use data-cy attributes for element selectors to improve test stability
Avoid using CSS classes or IDs that may change frequently
Use Cypress commands like cy.get('[data-cy="..."]') for selectors
Use explicit assertions to confirm actions succeeded
Automated Solution
Cypress
describe('Login Test Using data-cy Attributes', () => {
  beforeEach(() => {
    cy.visit('/login');
  });

  it('should login successfully using data-cy selectors', () => {
    cy.get('[data-cy="email-input"]').type('user@example.com');
    cy.get('[data-cy="password-input"]').type('Password123!');
    cy.get('[data-cy="login-button"]').should('be.visible').and('be.enabled').click();
    cy.url().should('include', '/dashboard');
  });
});

This Cypress test visits the login page before each test to ensure a fresh start.

It uses cy.get('[data-cy="..."]') to select elements by their data-cy attributes, which are stable and unlikely to change, making tests more reliable.

The test types the email and password into the respective inputs, then checks that the login button is visible and enabled before clicking it.

Finally, it asserts that the URL includes '/dashboard' to confirm successful login.

Common Mistakes - 3 Pitfalls
Using CSS classes or IDs for selectors instead of data-cy attributes
{'mistake': 'Not waiting for elements to be visible or enabled before interacting', 'why_bad': 'Interacting with elements too early can cause flaky tests or errors.', 'correct_approach': "Use Cypress assertions like .should('be.visible') and .should('be.enabled') before clicking or typing."}
{'mistake': 'Hardcoding selectors without attribute quotes or incorrect syntax', 'why_bad': 'Incorrect selector syntax causes tests to fail to find elements.', 'correct_approach': 'Always use correct CSS attribute selector syntax, e.g., cy.get(\'[data-cy="email-input"]\')'}
Bonus Challenge

Now add data-driven testing with 3 different sets of login credentials using data-cy selectors

Show Hint