
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 ) Example: cy . intercept ( ' GET ' , ' /api/users ' , { statusCode : 200 , body : [{ id : 1 , name : ' John ' }] }) 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 ' ) This loads data from: cypress/fixtures/users.json 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 ' }) Best Practices: Use fixtures for reusable mock data. Always alias important reque
Continue reading on Dev.to Webdev
Opens in a new tab



