We use cy.intercept() to watch or change network requests during tests. This helps us check if our app talks to servers correctly.
0
0
cy.intercept() for request interception in Cypress
Introduction
When you want to check if your app sends the right data to the server.
When the server is slow or not ready, and you want to test your app anyway.
When you want to fake server responses to test different situations.
When you want to make sure your app handles errors from the server well.
Syntax
Cypress
cy.intercept(method, url, response?)
method is the HTTP method like GET, POST, etc. It is optional.
url is the address or pattern of the request to catch.
Examples
This watches all GET requests to '/api/users' without changing them.
Cypress
cy.intercept('GET', '/api/users')
This catches POST requests to '/api/login' and sends back a fake success response.
Cypress
cy.intercept('POST', '/api/login', { statusCode: 200, body: { success: true } })
This intercepts any request to '/api/data' and replies with data from a file called 'data.json'.
Cypress
cy.intercept('/api/data', { fixture: 'data.json' })
Sample Program
This test fakes the server response for the user list. When the app asks for users, it gets one user named Alice. The test then checks if Alice's name appears on the page.
Cypress
describe('Test user API', () => { it('should show mocked user data', () => { cy.intercept('GET', '/api/users', { body: [{ id: 1, name: 'Alice' }] }) cy.visit('/users') cy.contains('Alice').should('be.visible') }) })
OutputSuccess
Important Notes
You can intercept requests before the app sends them to control test conditions.
Use cy.wait() with intercept to wait for requests to finish.
Intercepting helps make tests faster and more reliable by avoiding real network calls.
Summary
cy.intercept() lets you watch or change network requests in tests.
It helps test how your app handles server data and errors.
You can fake responses to test different scenarios easily.