0
0
Cypresstesting~8 mins

Chaining selectors in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Chaining selectors
Folder Structure
  cypress/
  ├── e2e/
  │   ├── login.cy.js
  │   ├── dashboard.cy.js
  │   └── userProfile.cy.js
  ├── support/
  │   ├── commands.js       <-- Custom commands with chained selectors
  │   ├── selectors.js      <-- Central place for reusable selectors
  │   └── e2e.js            <-- Global setup
  ├── fixtures/
  │   └── user.json
  cypress.config.js         <-- Configuration for baseUrl, env
  package.json
  
Test Framework Layers
  • Test Layer (cypress/e2e): Contains test files that use chained selectors to find elements step-by-step for clarity and reliability.
  • Support Layer (cypress/support): Holds reusable selector definitions and custom commands that implement chaining for cleaner tests.
  • Fixtures: Test data like user info to drive tests.
  • Config: Central place for environment settings, base URLs, and browser options.
Configuration Patterns

Use cypress.config.js to set baseUrl and environment variables.

Selectors are stored in selectors.js as functions returning chained Cypress commands for reusability and easy updates.

Example environment setup:

  export default defineConfig({
    e2e: {
      baseUrl: 'https://example.com',
      env: {
        username: 'testuser',
        password: 'password123'
      }
    }
  })
  
Test Reporting and CI/CD Integration

Use Cypress built-in reporter or integrate with mochawesome for detailed HTML reports.

CI/CD pipelines run tests headlessly using cypress run command and publish reports.

Chaining selectors improves test stability, reducing flaky failures in CI.

Best Practices for Chaining Selectors
  • Define selectors in one place (selectors.js) to avoid duplication and ease maintenance.
  • Use chaining to narrow down elements step-by-step, mimicking how a user sees the page.
  • Prefer data attributes (e.g., data-cy) for selectors to avoid brittle tests.
  • Write custom commands for common chained selector patterns to keep tests clean.
  • Use explicit waits or assertions after chaining to ensure elements are ready before interacting.
Self Check

Where in this folder structure would you add a new chained selector for a "Search" input field used across multiple tests?

Key Result
Organize Cypress tests with reusable chained selectors in support files for clear, stable, and maintainable tests.