0
0
Cypresstesting~3 mins

Why cy.intercept() for request interception in Cypress? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could control every server response in your tests with a single command?

The Scenario

Imagine testing a website that loads data from a server. You refresh the page and wait for the server to respond every time. Sometimes the server is slow or the data changes unexpectedly. You have to check the results manually each time.

The Problem

Manually waiting for server responses is slow and tiring. You might miss errors or get different results each time. It is hard to test how your app behaves with different server responses or errors. This makes testing unreliable and frustrating.

The Solution

Using cy.intercept() lets you catch and control server requests in your tests. You can fake responses, delay them, or simulate errors easily. This makes your tests faster, stable, and predictable without depending on the real server.

Before vs After
Before
cy.visit('/page')
// wait and check data manually
cy.wait(5000)
cy.get('.data').should('contain', 'expected')
After
cy.intercept('GET', '/api/data', { fixture: 'data.json' })
cy.visit('/page')
cy.get('.data').should('contain', 'expected')
What It Enables

You can test your app's behavior under any server condition instantly and reliably.

Real Life Example

Testing a shopping site where you simulate out-of-stock items or server errors without changing the real backend.

Key Takeaways

Manual server testing is slow and unreliable.

cy.intercept() lets you control server responses in tests.

This makes tests faster, stable, and easier to write.