How to Use cy.intercept for Mocking in Cypress Tests
Use
cy.intercept in Cypress to stub or mock network requests by specifying the HTTP method and URL, then providing a mocked response. This lets you control API data during tests without hitting the real server.Syntax
The basic syntax of cy.intercept includes the HTTP method, the URL to intercept, and the mocked response or handler function.
- method: HTTP method like 'GET', 'POST', etc.
- url: The URL or pattern to match requests.
- response: The mocked data or function to send back.
javascript
cy.intercept(method, url, response)
Example
This example shows how to mock a GET request to '/api/users' and return a fixed list of users. The test visits a page and verifies the mocked data is displayed.
javascript
describe('Mock API with cy.intercept', () => { it('mocks GET /api/users response', () => { cy.intercept('GET', '/api/users', { statusCode: 200, body: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }], }).as('getUsers') cy.visit('/users') cy.wait('@getUsers') cy.get('[data-cy=user-name]').should('have.length', 2) cy.get('[data-cy=user-name]').first().should('contain.text', 'Alice') }) })
Output
Test passes if the page shows 2 user names: Alice and Bob, confirming the mock worked.
Common Pitfalls
Common mistakes when using cy.intercept include:
- Not using the correct URL or method, so the intercept never matches.
- Forgetting to wait for the intercepted request with
cy.wait(), causing flaky tests. - Mocking responses without proper status codes or structure, leading to unexpected app behavior.
Always verify your intercept matches the actual request and use aliases to wait for them.
javascript
/* Wrong: URL mismatch, intercept won't trigger */ cy.intercept('GET', '/api/userz', { body: [] }) /* Right: Correct URL and alias for waiting */ cy.intercept('GET', '/api/users', { body: [] }).as('getUsers') cy.wait('@getUsers')
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| method | HTTP method to intercept | 'GET', 'POST', 'PUT' |
| url | URL or pattern to match requests | '/api/users', '**/login' |
| response | Mocked response data or function | { statusCode: 200, body: {...} } |
| alias | Name to reference the intercept | .as('getUsers') |
| cy.wait() | Wait for the intercepted request | cy.wait('@getUsers') |
Key Takeaways
Use cy.intercept(method, url, response) to mock network requests in Cypress.
Always assign an alias with .as() and wait for the request with cy.wait() to ensure test stability.
Match the exact HTTP method and URL pattern to successfully intercept requests.
Mock responses should include realistic status codes and data structure to avoid test errors.
cy.intercept helps isolate frontend tests from backend dependencies by controlling API responses.