The Difference Between Stub and Intercept

The Difference Between Stub and Intercept

Ferenc Almasi β€’ 2021 October 27 β€’ Read time 1 min read
  • twitter
  • facebook

The difference between cy.stub and cy.intercept is that:

  • cy.stub can be used for stubbing functions to record their usage, or control their behavior.
  • cy.intercept can be used for intercepting network requests to return mock values.

For example, to stub a method of an object, you can call the following in Cypress:

Copied to clipboard! Playground
const user = {
    // Get method for getting a user based on an ID
    get(id) { ... }
};

cy.stub(user, 'get')
  .withArgs('age')
  .returns(30);

The above code example will stub the user.get method with an argument of age, and it forces the function to return 30. On the other hand, you can intercept network requests in the following way:

Copied to clipboard!
cy.intercept('/api', { fixtures: 'response.json' });

This will intercept any requests made to /api and forces it to respond with the contents of the response.json file.

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
The Difference Between Stub and Intercept
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.