How to Intercept Network Requests in Cypress
To intercept network requests in Cypress we can use the cy.intercept
command, passing the URL we want to intercept, and a mock JSON file that we want to return as a response:
Copied to clipboard!
// Using a fixture as a mock response:
cy.intercept('/api', { fixtures: 'response.json' });
We can also customize the parameters by passing a configuration object to the intercept
command:
If you want to specifically test a failure path and see how your application behaves when things go wrong, we can also mock the status code and return 500 for example:
Copied to clipboard!
cy.intercept('GET', '/api', {
statusCode: 500
});
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews