0
0
Cypresstesting~8 mins

data-cy attributes for test stability in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - data-cy attributes for test stability
Folder Structure
cypress/
├── e2e/                  # Test specs using data-cy selectors
│   ├── login.cy.js
│   ├── dashboard.cy.js
│   └── userProfile.cy.js
├── fixtures/             # Test data files (JSON)
│   └── users.json
├── support/              # Custom commands and utilities
│   ├── commands.js       # Custom commands using data-cy
│   └── index.js          # Support file loaded before tests
cypress.config.js         # Cypress configuration file
package.json              # Project dependencies and scripts
    
Test Framework Layers
  • Test Specs (cypress/e2e): Use data-cy attributes to locate elements reliably. Example: cy.get('[data-cy=submit-button]').
  • Support Layer (cypress/support): Define custom commands that use data-cy selectors to keep tests clean and stable.
  • Fixtures: Store test data separately to keep tests maintainable and reusable.
  • Configuration: Manage environment variables and base URLs in cypress.config.js.
Configuration Patterns

Use cypress.config.js to manage environments and settings:

import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    baseUrl: 'https://staging.example.com',
    env: {
      username: 'testuser',
      password: 'password123'
    },
    setupNodeEvents(on, config) {
      // implement node event listeners here
    }
  }
})
    

Use data-cy attributes in HTML elements to avoid brittle selectors that depend on classes or IDs that may change.

Test Reporting and CI/CD Integration
  • Use Cypress built-in reporter for clear pass/fail results.
  • Integrate with CI tools like GitHub Actions or Jenkins to run tests on every push.
  • Generate HTML or JSON reports using plugins like mochawesome for detailed insights.
  • Use screenshots and video recordings on test failures to help debugging.
Best Practices for Using data-cy Attributes
  1. Use data-cy only for testing: Keep these attributes separate from styling or functionality to avoid accidental changes.
  2. Make data-cy values meaningful and stable: Use descriptive names like data-cy="login-button" instead of generic ones.
  3. Do not rely on classes or IDs for tests: These often change with design updates, causing flaky tests.
  4. Centralize selectors in custom commands: Define commands like cy.login() that use data-cy selectors internally.
  5. Collaborate with developers: Ensure data-cy attributes are added consistently during development.
Self Check

Where in this folder structure would you add a new data-cy selector for a "submit" button used across multiple tests?

Key Result
Use data-cy attributes as stable, dedicated selectors in Cypress tests to improve test reliability and maintainability.