cy.intercept is one of the most used commands in real Cypress work, and it is a main reason teams pick Cypress for apps with a busy API. You cannot run it in the editor on this site, because our browser engine does not implement request interception. Everything below is real, working Cypress. Use it on a local project and it behaves exactly as described.
Here is a bug that a normal test will never catch.
You create a contact named Dana Fox at the company FoxLabs. The green message appears. The new row appears in the table. Everything looks correct.
But the app sent the wrong company name to the server. You only find out days later, when someone opens the contact and the company is empty.
The screen looked right. The data was wrong. To catch this, you need to look at the request. The message the app sends to the server.
Cypress can watch requests for you. You do it in two steps.
Step 1: tell Cypress what to watch.
cy.intercept('POST', '/api/contacts').as('saveContact');
cy.intercept means "watch for this request". POST is the type of request, and /api/contacts is the address. .as('saveContact') gives it a nickname so you can talk about it later. Put this line before the click that causes the request.
Step 2: wait for it.
cy.get('[data-testid="save-contact"]').click();
cy.wait('@saveContact');
The @ means "the request I nicknamed saveContact". Cypress now waits for that exact request to finish. Not 2 seconds. Not 5 seconds. It waits for the real thing, however long it takes.
Now you can check what was sent:
cy.wait('@saveContact').then((interception) => {
expect(interception.request.body.name).to.equal('Dana Fox');
expect(interception.request.body.company).to.equal('FoxLabs');
expect(interception.response.statusCode).to.equal(201);
});
interception holds both sides: what your app sent (request) and what the server answered (response). Now the wrong company name fails the test immediately.
One thing to keep in mind. Most of the time you should still check the screen, because that is what your user sees. Use the network when:
- You need to check the data that was sent.
- Nothing on the screen changes yet, and you need the request to finish first.
Remember this: wait for a real request, never for a number of seconds.
You can practise the instinct behind this without intercept. The problem Prove a contact was actually saved makes you prove the save really happened instead of trusting the green message.
Reference: Network requests.