0
0
Cypresstesting~8 mins

cy.wait() for explicit waiting in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - cy.wait() for explicit waiting
Folder Structure
cypress/
├── e2e/                  # Test files (specs) go here
│   └── example.cy.js
├── fixtures/             # Test data files (JSON, etc.)
│   └── userData.json
├── support/              # Custom commands and reusable utilities
│   ├── commands.js
│   └── e2e.js            # Global support file
cypress.config.js         # Cypress configuration file
Test Framework Layers
  • Test Specs (e2e/): Contains test scripts that use cy.wait() for explicit waits when needed.
  • Support Layer (support/): Holds reusable commands and utilities to wrap cy.wait() or other wait strategies.
  • Fixtures (fixtures/): Stores test data to drive tests without hardcoding values.
  • Configuration (cypress.config.js): Defines environment settings, base URLs, and global timeouts.
Configuration Patterns

Use cypress.config.js to set global timeouts and base URLs. For example:

import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    baseUrl: 'https://example.com',
    defaultCommandTimeout: 8000,  // default wait time for commands
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
  },
})

Use environment variables to switch between test environments:

npx cypress run --env environment=staging

Inside tests, access with Cypress.env('environment').

Test Reporting and CI/CD Integration
  • Use built-in Cypress test runner reports for local debugging.
  • Integrate with CI tools (GitHub Actions, Jenkins) to run tests on push or pull requests.
  • Use reporters like mochawesome for detailed HTML reports.
  • Configure CI to fail builds if tests using cy.wait() fail, ensuring explicit waits do not mask timing issues.
Best Practices for Using cy.wait()
  • Prefer waiting for specific events: Use cy.intercept() and cy.wait() with aliases instead of fixed time waits.
  • Avoid fixed time waits: Fixed waits like cy.wait(5000) slow tests and can cause flakiness.
  • Use explicit waits only when necessary: For example, waiting for animations or backend responses not covered by intercepts.
  • Keep waits short: Use the minimum wait time needed to reduce test duration.
  • Wrap common wait logic: Create custom commands in support/commands.js to reuse explicit wait patterns.
Self Check

Where in this folder structure would you add a custom command that wraps cy.wait() to wait for a specific API call to finish?

Key Result
Organize Cypress tests with clear folder layers, use cy.wait() sparingly with intercepts, and configure environments for reliable explicit waits.