The Difference Between Stub and Intercept
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:
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews