How to Use cy.intercept in Cypress for Network Stubbing and Testing
Use
cy.intercept in Cypress to spy on or stub network requests by specifying the HTTP method and URL pattern. It lets you control responses or observe requests during tests, improving test reliability and speed.Syntax
The basic syntax of cy.intercept includes specifying the HTTP method, the URL or URL pattern to intercept, and optionally a response to stub or a callback to modify the request or response.
- method: HTTP method like GET, POST, etc.
- url: URL string or pattern to match requests
- response: (optional) object or function to stub the response
javascript
cy.intercept(method, url, response?)
Example
This example shows how to intercept a GET request to '/api/users' and stub a custom response. It demonstrates controlling the server response to test UI behavior without relying on the real backend.
javascript
describe('User API test', () => { it('stubs GET /api/users with custom data', () => { cy.intercept('GET', '/api/users', { statusCode: 200, body: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }], }).as('getUsers') cy.visit('/users') cy.wait('@getUsers').its('response.statusCode').should('eq', 200) cy.get('.user-list').should('contain.text', 'Alice').and('contain.text', 'Bob') }) })
Output
Test passes if the stubbed users appear on the page and the intercepted request returns status 200.
Common Pitfalls
Common mistakes when using cy.intercept include:
- Not using
.as()to alias the intercept for easier waiting and assertions. - Incorrect URL patterns causing the intercept to not match requests.
- Forgetting to stub the response when needed, leading to flaky tests if the backend is slow or unavailable.
- Using
cy.route(legacy) instead ofcy.intercept.
javascript
/* Wrong: No alias and incorrect URL pattern */ cy.intercept('GET', '/api/userz', { body: [] }) /* Right: Correct URL and alias for waiting */ cy.intercept('GET', '/api/users', { body: [] }).as('getUsers')
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| method | HTTP method to intercept | 'GET', 'POST', 'PUT', etc. |
| url | URL or pattern to match requests | '/api/users', '**/login' |
| response | Stubbed response or callback | { statusCode: 200, body: {...} } or (req) => {...} |
| alias | Name to reference intercept | .as('getUsers') |
| wait | Wait for intercepted request | cy.wait('@getUsers') |
Key Takeaways
Use cy.intercept to spy on or stub network requests by specifying method and URL.
Always alias intercepts with .as() for easier waiting and assertions.
Stub responses to make tests faster and independent of backend availability.
Use URL patterns carefully to ensure intercept matches the intended requests.
Avoid legacy cy.route; prefer cy.intercept for modern Cypress tests.