How to Mock API Response in Cypress for Testing
Use
cy.intercept() in Cypress to mock API responses by intercepting network requests and providing custom data. This lets you test your app with controlled responses without hitting the real backend.Syntax
The basic syntax of cy.intercept() lets you intercept HTTP requests and mock their responses.
method: HTTP method like 'GET', 'POST'.url: The API endpoint to intercept.response: The mock data or object to return instead of the real response.
javascript
cy.intercept(method, url, response)
Example
This example shows how to mock a GET request to '/api/users' and return a fake user list. The test visits the page and verifies the mocked data is shown.
javascript
describe('Mock API response with Cypress', () => { it('should display mocked user 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') cy.get('.user').should('have.length', 2) cy.get('.user').first().should('contain.text', 'Alice') }) })
Output
Test passes if the page shows 2 users named Alice and Bob from the mocked response.
Common Pitfalls
Common mistakes when mocking API responses in Cypress include:
- Not using
cy.wait()to wait for the intercepted request, causing flaky tests. - Using incorrect URL patterns that don't match the actual request.
- Not aliasing the intercept with
.as()to reference it later. - Mocking only part of the response or missing required fields, causing UI errors.
javascript
/* Wrong way: No alias and no wait, test may fail */ cy.intercept('GET', '/api/users', { body: [{ id: 1, name: 'Alice' }] }) cy.visit('/users') cy.get('.user').should('have.length', 1) // May fail if request not finished /* Right way: Alias and wait */ cy.intercept('GET', '/api/users', { body: [{ id: 1, name: 'Alice' }] }).as('getUsers') cy.visit('/users') cy.wait('@getUsers') cy.get('.user').should('have.length', 1)
Quick Reference
| Command | Description |
|---|---|
| cy.intercept(method, url, response) | Intercepts HTTP request and mocks response |
| cy.intercept(...).as(aliasName) | Gives an alias to the intercept for waiting or referencing |
| cy.wait(aliasName) | Waits for the intercepted request to complete |
| cy.get(selector).should(...) | Asserts UI elements based on mocked data |
Key Takeaways
Use cy.intercept() to mock API responses by intercepting HTTP requests.
Always alias your intercept with .as() and wait for it with cy.wait() to avoid flaky tests.
Match the URL and method exactly to ensure the intercept works.
Provide complete mock response data to prevent UI errors.
Mocking API responses helps test your app reliably without backend dependency.