Network Stubbing with cy.intercept()
You'll learn how to control API responses in Cypress tests, allowing you to verify your UI handles different server scenarios without depending on real backend availability.
What Is Network Stubbing?
In Cypress, cy.intercept() lets you intercept HTTP requests and return mock responses instead of hitting actual servers. Think of it like a traffic controller at an intersection—you can redirect incoming API calls to wherever you want, returning success data, errors, or delays on demand.
This is similar to MSW but operates at Cypress's network layer, giving you E2E-specific control during test runs.
Why Stub Network Requests?
Real APIs are unpredictable: they might be slow, down, or return inconsistent data. By stubbing with cy.intercept(), you can:
- Test loading states by delaying responses
- Test error handling without breaking your backend
- Test edge cases (empty lists, special characters)
- Run tests faster and more reliably
The Basic Pattern
cy.intercept('GET', '/api/users', {
statusCode: 200,
body: [{ id: 1, name: 'Alice' }]
});
Now when your React app fetches /api/users, Cypress intercepts it and returns your mock data instead.
Testing Different States
// Test empty state
cy.intercept('GET', '/api/posts', { body: [] });
// Test error handling
cy.intercept('GET', '/api/posts', { statusCode: 500 });
// Test slow network
cy.intercept('GET', '/api/posts', { delay: 3000, body: mockPosts });
Each test can define exactly what server response it needs, making your tests deterministic and fast.
Key Takeaway: cy.intercept() gives you complete control over API responses in E2E tests, letting you verify your React app handles every server scenario correctly without needing a real backend.