Intercepting Network Requests in Cypress
In Cypress, you can intercept and manipulate network requests using its powerful cy.intercept()
command. This feature allows you to stub, spy on, modify, or wait for network requests and responses during your tests. Here’s how you can intercept network requests in Cypress:
Intercepting Network Requests
Basic Interception
To intercept network requests, you typically use cy.intercept()
with a route matcher and handler function. Here’s a basic example:
describe('Intercept Network Requests', () => {
it('should intercept and modify network request', () => {
cy.intercept('GET', '**/api/endpoint', (req) => {
// Modify request URL or headers if needed
req.url = 'https://mocked-api.com/data';
// Stub response data
req.reply({
statusCode: 200,
body: {
message: 'Mocked response data',
},
headers: {
'content-type': 'application/json',
},
delay: 1000, // Simulate delay if needed
});
});
// Visit your application where the request is made
cy.visit('https://your-app.com');
// Perform actions that trigger the network request
cy.get('.load-data-button').click();
// Assert on the response or behavior after interception
cy.contains('Mocked response data').should('be.visible');
});
});
Advanced Interception
You can also use cy.intercept()
to stub multiple requests or handle different scenarios based on conditions:
describe('Advanced Network Interception', () => {
beforeEach(() => {
// Intercept multiple requests with different handlers
cy.intercept('GET', '**/api/users', (req) => {
req.reply({ fixture: 'users.json' }); // Respond with fixture data
});
cy.intercept('POST', '**/api/login', (req) => {
req.reply((res) => {
// Modify response based on request body or headers
if (req.body.username === 'admin') {
res.send({ token: 'mocked-token-admin' });
} else {
res.send({ token: 'mocked-token-user' });
}
});
});
});
it('should intercept and handle different requests', () => {
// Perform actions triggering the intercepted requests
cy.visit('https://your-app.com');
// Example: Trigger a GET request
cy.get('.load-users-button').click();
// Example: Trigger a POST request
cy.get('#username').type('admin');
cy.get('#password').type('password');
cy.get('#login-button').click();
// Assert on the response or application behavior
cy.contains('Welcome, Admin').should('be.visible');
});
});
Published on: Jun 28, 2024, 03:33 AM