0
0
Cypresstesting~8 mins

Waiting for requests (cy.wait with alias) in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Waiting for requests (cy.wait with alias)
Folder Structure
  cypress/
  ├── e2e/
  │   ├── login.cy.js          # Test files
  │   ├── dashboard.cy.js
  │   └── apiRequests.cy.js    # Tests using cy.wait with alias
  ├── fixtures/                # Static test data
  │   └── user.json
  ├── support/
  │   ├── commands.js          # Custom commands
  │   └── e2e.js               # Global setup
  └── cypress.config.js        # Configuration file
  
Test Framework Layers
  • Test Files (cypress/e2e/): Contains test scripts that use cy.intercept to spy or stub network requests and cy.wait with aliases to wait for them.
  • Support Layer (cypress/support/): Holds reusable commands and global hooks to set up intercepts or common behaviors.
  • Fixtures (cypress/fixtures/): Static JSON or other files used as mock data for API responses or test inputs.
  • Configuration (cypress.config.js): Defines environment variables, base URLs, and browser settings.
Configuration Patterns

Use cypress.config.js to define base URLs and environment variables for different environments (dev, staging, prod). For example:

  export default defineConfig({
    e2e: {
      baseUrl: 'https://example.com',
      env: {
        apiUrl: 'https://api.example.com'
      },
      setupNodeEvents(on, config) {
        // implement node event listeners here
      }
    }
  })
  

In tests, use cy.intercept with aliases to listen for specific API calls. Use cy.wait('@alias') to pause test execution until the request finishes, ensuring stable tests.

Test Reporting and CI/CD Integration
  • Use Cypress built-in reporter for test results in the terminal.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests on every push or pull request.
  • Generate HTML reports using plugins like mochawesome for detailed test reports.
  • Use screenshots and video recordings on test failures for easier debugging.
Best Practices
  • Use cy.intercept with meaningful aliases: Name aliases clearly to reflect the request purpose, e.g., @getUser.
  • Always wait for requests before asserting UI changes: Use cy.wait('@alias') to ensure the app has received data before checking results.
  • Keep intercepts and waits close to the test steps: This improves readability and debugging.
  • Use fixtures for consistent mock data: This helps tests be reliable and repeatable.
  • Avoid arbitrary waits like cy.wait(5000): They slow tests and cause flakiness.
Self Check

Where in this folder structure would you add a new alias for waiting on the "POST /login" API request?

Key Result
Use cy.intercept with aliases and cy.wait('@alias') in test files to reliably wait for network requests.