Network Interception with cy.intercept
Intermediatev1.0.0
Master cy.intercept for API mocking, response stubbing, request validation, and network error simulation to create deterministic, fast Cypress tests.
Content
Overview
cy.intercept is Cypress's tool for controlling network requests. Stub API responses for deterministic tests, validate request payloads, simulate errors, and control timing — all without a running backend.
Why This Matters
- -Deterministic — tests do not depend on backend state or availability
- -Fast — no real API calls means faster test execution
- -Edge cases — easily simulate errors, slow responses, and empty states
- -Parallel-safe — tests do not interfere with each other via shared APIs
How It Works
Stub API Responses
Use Fixture Files
Validate Request Payloads
Simulate Errors
Simulate Slow Responses
Best Practices
- -Always alias intercepts with
.as('name')andcy.wait('@name')before assertions - -Use fixture files for large response payloads
- -Test both success and error responses for every API endpoint
- -Use route matching with wildcards:
/api/users*to catch query params - -Stub third-party APIs (analytics, payment) to avoid external dependencies
Common Mistakes
- -Not waiting for the intercept alias (asserting before response arrives)
- -Using
cy.wait(ms)instead ofcy.wait('@alias') - -Forgetting to intercept DELETE/PUT/PATCH methods (only GET by default)
- -Not testing error states and edge cases with intercept
FAQ
Discussion
Loading comments...