0
0
Cypresstesting~8 mins

Stubbing responses in Cypress - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Stubbing responses
Folder Structure
cypress/
├── e2e/                  # Test specs
│   └── example.cy.js     # Example test with stubbing
├── fixtures/             # Static test data files (JSON, etc.)
│   └── user.json         # Sample stub data
├── support/              # Custom commands and utilities
│   ├── commands.js       # Custom Cypress commands
│   └── index.js          # Support file loaded before tests
cypress.config.js         # Cypress configuration file
Test Framework Layers
  • Test Specs (cypress/e2e): Contains test files where stubbing is used to simulate server responses.
  • Fixtures (cypress/fixtures): Holds JSON or other files with stub data to return during tests.
  • Support (cypress/support): Custom commands to simplify stubbing setup and reusable utilities.
  • Configuration (cypress.config.js): Defines base URLs, environment variables, and test settings.
Configuration Patterns
  • Environment Variables: Use env in cypress.config.js to set API base URLs or toggle stubbing on/off.
  • Fixtures: Store stub response data in cypress/fixtures for easy reuse and maintenance.
  • Custom Commands: Define commands like cy.stubResponse() in cypress/support/commands.js to centralize stubbing logic.
  • Browser and Test Settings: Configure timeouts and retries in cypress.config.js to handle async stubbing behavior.
Test Reporting and CI/CD Integration
  • Test Reports: Use Cypress built-in reporter or integrate with tools like Mochawesome for detailed HTML reports showing stubbed test results.
  • CI/CD: Run Cypress tests with stubbing enabled in pipelines to ensure tests are fast and reliable without depending on real backend.
  • Artifacts: Save screenshots and videos on test failures to help debug stub-related issues.
Best Practices
  • Use Fixtures for Stub Data: Keep stub responses in separate files for clarity and easy updates.
  • Centralize Stubbing Logic: Create reusable custom commands to avoid repeating stubbing code in tests.
  • Stub Only What's Needed: Stub specific API calls relevant to the test to keep tests realistic.
  • Keep Tests Independent: Avoid relying on real backend to make tests fast and stable.
  • Document Stub Behavior: Comment why and how stubs are used to help team understanding.
Self Check

Where in this folder structure would you add a new stub response JSON file for a user profile API?

Key Result
Use fixtures and custom commands in Cypress to stub API responses for fast, reliable tests.