0
0
Cypresstesting~8 mins

Dynamic response stubbing in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Dynamic response stubbing
Folder Structure
    cypress/
    ├── e2e/                  # Test specs
    │   └── dynamicStub.cy.js # Tests using dynamic response stubbing
    ├── fixtures/             # Static test data
    │   └── example.json
    ├── support/              # Custom commands and utilities
    │   ├── commands.js       # Custom Cypress commands
    │   └── index.js          # Support file loaded before tests
    ├── plugins/              # Plugins for Cypress (optional)
    └── cypress.config.js     # Cypress configuration file
    
Test Framework Layers
  • Test Specs (e2e/): Contains test files that define test cases using dynamic stubbing with cy.intercept().
  • Fixtures (fixtures/): Holds static JSON or other data files used to stub responses when needed.
  • Support (support/): Contains reusable commands and utilities, such as custom commands to simplify dynamic stubbing logic.
  • Configuration (cypress.config.js): Defines environment variables, base URLs, and browser settings.
Configuration Patterns

Use cypress.config.js to manage environments and base URLs:

import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    baseUrl: 'https://example.com',
    env: {
      apiUrl: 'https://api.example.com',
      userToken: 'test-token'
    },
    setupNodeEvents(on, config) {
      // plugins can be added here
    }
  }
})
    

In tests, access environment variables with Cypress.env() to dynamically stub responses based on environment or test data.

Test Reporting and CI/CD Integration
  • Use built-in Cypress reporter or integrate with mochawesome for detailed HTML reports.
  • Configure CI pipelines (GitHub Actions, Jenkins, GitLab CI) to run Cypress tests headlessly with cypress run.
  • Store test artifacts like screenshots and videos for failed tests to help debugging dynamic stubbing issues.
  • Use environment variables in CI to switch API endpoints or stub data dynamically.
Best Practices for Dynamic Response Stubbing
  1. Use cy.intercept() with functions to dynamically modify responses based on request data or test state.
  2. Keep stub logic in support commands to reuse dynamic stubbing patterns and keep tests clean.
  3. Use fixtures for static parts of stubbed responses and merge dynamically generated data as needed.
  4. Isolate tests by resetting stubs before each test to avoid cross-test interference.
  5. Log intercepted requests and responses during test runs to help debug dynamic stubbing behavior.
Self Check

Where in this folder structure would you add a reusable custom command to simplify dynamic response stubbing?

Key Result
Organize Cypress tests with clear folder layers and use cy.intercept() with dynamic logic for flexible response stubbing.