This builds on cy.intercept, so it is also something you run on a local project rather than in the editor here. The technique is standard on real Cypress teams, and interviewers ask about its trade-off often.
Your product manager asks a fair question: "What does the app show when the server is down?"
You want to test it. But how? You cannot break the real server just to run a test.
You can make Cypress answer the request for you. This is called stubbing: your test gives a fake answer instead of letting the request reach the real server.
Here is a server error, in a few lines:
cy.intercept('GET', '/api/contacts', {
statusCode: 500,
body: { error: 'Server error' },
}).as('contactsFail');
cy.visit('/');
cy.wait('@contactsFail');
cy.get('[data-testid="error-banner"]').should('contain', 'Something went wrong');
Look at the second argument of cy.intercept. Before, you passed nothing and Cypress just watched. Now you pass an object, and Cypress answers with it. statusCode: 500 means "server error". The real server is never called.
You can use the same trick for other hard situations:
- An empty list, to check the "no contacts yet" screen.
- A list with 500 contacts, to check that the page does not break.
- A very slow answer, to check your loading spinner.
Stubbing also makes tests steadier, because the answer is the same on every run. Nobody can break your test by changing data in a shared test database.
Now the part many people skip. Stubbing has a real cost.
A stubbed test does not check the server at all. Imagine the backend team renames a field from name to fullName. Your stub still returns name, so your test still passes. Your suite is green and the real app is broken.
This is not a made-up example. A team I worked with stubbed almost every request because it made the suite fast and steady. It was fast and steady for months. Then an API change went out, every screen showed empty names, and all 200 tests were green while support handled angry emails.
So teams usually split it like this:
- Stub the situations that are hard to create: errors, empty lists, huge lists, slow answers.
- Do not stub your main happy path. Let at least one test go all the way to the real server, so a change in the API breaks something.
Remember this: stub to reach a state you cannot create easily. Always keep one real path, or a broken API will pass your tests.
Reference: cy.intercept.