DEV Community

Elabid Asmaa
Elabid Asmaa

Posted on

Cypress Interceptors (E2E Testing)

cy.intercept() in Cypress allows you to spy on, modify, or mock HTTP requests during end-to-end tests.

It is mainly used to:

  • Prevent real API calls

  • Mock backend responses

  • Control test scenarios

  • Wait for network requests before assertions

Basic Syntax:

cy.intercept(method, url, response)
Enter fullscreen mode Exit fullscreen mode

Example:

cy.intercept('GET', '/api/users', {
  statusCode: 200,
  body: [{ id: 1, name: 'John' }]
})
Enter fullscreen mode Exit fullscreen mode

This mocks the API response instead of calling the real backend.

Mocking API Responses

Intercept can return a custom response.

cy.intercept('GET', '/api/users', {
  fixture: 'users.json'
}).as('getUsers')
Enter fullscreen mode Exit fullscreen mode

This loads data from:

cypress/fixtures/users.json
Enter fullscreen mode Exit fullscreen mode

Benefits:

Stable tests

Independent from backend availability

Modifying Requests

You can change request data before it reaches the server.

cy.intercept('POST', '/api/login', (req) => {
  req.body.username = 'test-user'
})
Enter fullscreen mode Exit fullscreen mode

Best Practices:

  • Use fixtures for reusable mock data.

  • Always alias important requests with .as().

  • Avoid intercepting too many endpoints to keep tests realistic.

  • Use intercepts mainly for network stability and deterministic tests.

This makes E2E tests faster, deterministic, and independent from backend state.

Top comments (0)