How to Intercept Network Requests in Cypress

How to Intercept Network Requests in Cypress

Ferenc Almasi β€’ Last updated 2021 October 25 β€’ Read time 1 min read
  • twitter
  • facebook

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:

Copied to clipboard! Playground
cy.intercept({
  method: 'GET',
  query: {
    limit: 10
  },
  path: '/api'
});

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:

Learn Cypress with Educative
How to Intercept Network Requests in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.