What is cy.intercept and where exactly does the interception happen?
cy.intercept captures the HTTP requests the page makes and lets a test observe or replace them. When the method and URL match, Cypress either records the exchange (a spy), returns its own response (a stub), or lets the request through and allows changing the real response. It sees traffic leaving the browser (fetch, XHR, third-party scripts), but not WebSocket messages or cy.request calls.
Cypress · Network
A test depends on an outside API that is sometimes slow and sometimes down. How do you make it stable?
A product page loads data from a backend that on the test environment is sometimes slow and sometimes returns somebody else’s data. The test goes red for a reason that is not a UI bug. cy.intercept lets you see the request the page made and, when needed, answer in place of the server. This lesson explains what it sees, how it works and where its abilities end.
How it works and why. You register a route: a method, a URL (a string, a glob or a regular expression) and, if needed, other conditions. Every HTTP request of the page is compared with the routes. When a route matches, Cypress either just records the exchange (a spy), or returns its own response (a stub), or lets the request reach the server and lets you change the real response. The application code does not have to be touched: what left the browser is intercepted, so fetch, XHR, libraries and third-party scripts are all visible alike.
The path of a request
Figure 1. The route sits between the page and the network and decides the fate of every request.
According to the Cypress documentation, since version 16 interception in Chrome, Chromium and Edge happens on the browser’s native network layer, while Firefox, WebKit and Electron still send traffic through a proxy in the Cypress Node process. For a test there is almost no difference: the API is the same in every browser.
Example: from a backend dependency to controlled data.
Two modes of one route
spy
Observe
The request goes to the real server. Cypress only records the request and the response, and you can check them through an alias.
stub
Replace
The request never reaches the server: the test supplies the response (fixture, body, status, delay).
Figure 2. A spy and a stub are two equal tools for different jobs, not “bad” and “good”.
A test that relies on the real backend checks the number of products the environment returned and breaks when the data changes:
// depends on the data of the environment
cy.visit('/products');
cy.get('[data-cy=product]').should('have.length', 3);
With a stub the test sets the data itself, and an alias lets it wait for the request:
cy.intercept('GET', '/api/products*', {
fixture: 'products.json', // three products
}).as('products');
cy.visit('/products');
cy.wait('@products');
cy.get('[data-cy=product]').should('have.length', 3);
// spy: the request goes to the real server, we only watch
cy.intercept('GET', '/api/profile').as('profile');
Both calls have a method and a URL. The glob /api/products* also matches a query string (?page=2) but not /api/products/12, because * does not cross /.
Limits and alternatives.cy.intercept works with HTTP requests of the page. It does not intercept WebSocket messages. Requests made by cy.request are not seen either: Cypress makes them from Node, not the page. A stub does not prove that the real backend returns the same data: if a fixture drifts from the contract, the UI test stays green and production breaks. So keep at least a few end-to-end tests against the real backend and check fixtures against the API schema.
And in Playwright:
page.route() intercepts the requests of a page and context.route() those of the whole context. Unlike Cypress, a WebSocket can also be intercepted and mocked, through page.routeWebSocket() (since version 1.48).
Common mistakes.
Registering the route after cy.visit or a click: the request has already gone, and cy.wait times out.
A glob that is too wide (for example **/api/**) with a fixture: every request gets that response, not just one.
Mocking everything and checking nothing against the real backend: the test verifies a fixture, not the system.
Expecting cy.request or a WebSocket to be intercepted: routes do not see those channels.
Check yourself
A test registers cy.intercept('GET', '/api/orders').as('orders') after cy.visit('/orders'), and cy.wait('@orders') times out although the page showed orders. Why?
Answer
A route catches only requests made after it was registered. The page had already requested /api/orders while loading. Register the route before cy.visit or before the action that triggers the request.
Will cy.intercept see a cy.request('/api/orders') call from the same test?
Answer
No. cy.request is executed by Cypress from Node, bypassing the page, while cy.intercept works with requests the page makes. A test’s own API calls do not need interception: the response comes back to the test anyway.
Related lessons: “How do you wait for a request and check it through an alias?”, “How do you replace or change a server response?”, “Why must an intercept be set before the action, and what happens if there are several on one URL?”, “What is cy.request and how does it differ from cy.intercept?”.
In an interview.Junior:cy.intercept intercepts the HTTP requests of the page. You can only observe and check the request and the response (a spy) or replace the response with a fixture or a body (a stub). It does not intercept WebSockets. Middle/Senior: I register the route before the action. I use a spy to wait for the request and check what was sent, and a stub for states that are hard to reach on a real backend: an error, an empty list, a slow response. I check fixtures against the contract and keep a few tests without mocks so I do not stay green on invented data.
How do you wait for a request and check it through an alias?
A route is named with .as(), and cy.wait('@alias') waits for the next unconsumed request of that name and yields an interception object. The test checks what the page sent and received, without pauses. cy.wait does not check success, since a 500 is also a response, so the status is checked separately. If it reports no request, the method or URL of the route is usually wrong.
Cypress · Network
cy.wait('@orders') waits and fails after 5 seconds although the order was created. What is wrong?
After clicking “Place order” the page shows a success message, and the test checks only that. The backend may have received an empty cart or answered 201 with a wrong body, and the UI will not show it. An alias lets you wait for the request itself and check what the frontend sent and received. The lesson explains how this works and why cy.wait sometimes fails although the request happened.
How it works and why..as('orders') gives the route a name. From then on every request that matches the route is recorded by Cypress under that name. cy.wait('@orders') takes the next request not yet consumed, waits for it to finish and yields an interception object with request and response. The first cy.wait takes the first match, the second one with the same alias takes the second, and so on. So two calls are needed when the page made two requests.
The order of checking a request
Figure 1. The alias is created before the action and waited for after it.
Two timeouts decide how long cy.wait waits: requestTimeout (5 seconds by default) for the request to appear and responseTimeout (30 seconds) for the response. If the request never appeared, the message says no request with that alias was made, which is almost always a wrong method or URL in the route.
Example: from a pause to checking the request.
Weak
cy.wait(2000) and a UI check
The pause guesses the time and says nothing about what the page sent. The request could carry an empty cart and the “Success” message would still appear.
Better
an alias and a request/response check
The test waits for the request itself and checks the body and the status. There are no pauses, and the step finishes as soon as the response arrives.
cy.intercept('POST', '/api/orders').as('createOrder');
cy.get('[data-cy=checkout]').click();
cy.wait('@createOrder').then(({ request, response }) => {
expect(request.body.items).to.have.length(2);
expect(response?.statusCode).to.eq(201);
});
// the same through its: the check is retried until the timeout
cy.get('@createOrder')
.its('response.statusCode')
.should('eq', 201);
Here cy.wait yields the interception and .then checks the request body (the number of items) and the response status. A 500 is also a response, so cy.wait does not fail in that case: checking the status is up to you.
Limits and alternatives. Several requests can be waited for with an array: cy.wait(['@a', '@b']) waits for both. GraphQL sends everything to one URL, so the alias is set dynamically in a handler: if (req.body.operationName === 'Login') req.alias = 'login'. An alias lives only within a test: routes are reset before every test, so register them again in each test, for example in beforeEach.
And in Playwright:
There are no aliases: the wait for a request is created before the action and awaited after it.
An extra cy.wait(2000) next to cy.wait('@alias'): the alias already waits exactly as long as needed.
The method or URL in the route does not match the real request (/api/orders against /api/v2/orders/): cy.wait waits for a request that does not exist.
One cy.wait for two requests: the second stays unchecked, and a later cy.wait with that alias will take it rather than a new one.
Assuming cy.wait checks success: it only waits, the status must be checked separately.
Check yourself
A page calls GET /api/items twice (the initial load and a refresh after a click). What does each of two cy.wait('@items') yield?
Answer
The first yields the interception of the first request, the second that of the second. Each cy.wait with one alias takes the next match not yet consumed.
The user sees the order in the UI, but cy.wait('@createOrder') says there was no request. What do you check first?
Answer
The route match: method, URL and the time of registration. Often the route is written as POST /api/orders while the app calls /api/v2/orders/, or the route was registered after the action. The Cypress command log shows the real request.
Related lessons: “What is cy.intercept and where exactly does the interception happen?”, “Why must an intercept be set before the action, and what happens if there are several on one URL?”, “How do you check the status, body and headers of a response?”, “Why is cy.wait(3000) an antipattern and what to use instead?”.
In an interview.Junior: I register cy.intercept with an alias, perform the action and call cy.wait on the alias. It returns the request and the response, so I check the body and the status. Middle/Senior: Instead of pauses I wait for a specific request, and tune requestTimeout and responseTimeout if the backend is slow. For GraphQL I set an alias by operationName. I check the status explicitly, because cy.wait also passes on a 500.
How do you replace or change a server response?
A response is replaced with a static object as the third argument, or with a handler that calls req.reply() or req.continue(cb). A static response (body or fixture, statusCode, delay, forceNetworkError) suits a 500 error, an empty list or a slow network. After reply the request never reaches the server, while continue lets it through and the callback only edits the real response. The stub body shape comes from the contract, not guesswork.
Cypress · Network
How do you check that the UI shows a 500 error and a slow network when the backend works without failures?
A statistics page has a “Could not load” banner and a spinner for a slow response. A real server does not produce such states on demand. cy.intercept does: you can answer with an error, delay the response or change just one field of the real one. The lesson covers three ways and when to choose which.
How it works and why. The third argument can be a static response: body or fixture, statusCode, headers, delay, throttleKbps or forceNetworkError. When you need logic you pass a handler req => { … } instead. In it req.reply() answers itself and the request does not go to the server. req.continue(res => …) lets the request reach the server and lets you change the real response before the page gets it. A handler that calls none of these passes the request to the next match and finally to the server.
Three ways to respond
Figure 1. The difference is whether the request reaches the server and where the response comes from.
Example: states you cannot trigger on a real backend.
Static
A fixed state
Fits when the response is always the same: a 500 error, an empty list, a slow network.
Handler
State depends on the request
Needed when the response depends on the request body or parameters or only part of the real one changes.
// server error
cy.intercept('GET', '/api/stats', {
statusCode: 500,
body: { error: 'boom' },
});
// slow network
cy.intercept('GET', '/api/stats', {
fixture: 'stats.json',
delay: 2000,
});
// the real response, with one field replaced
cy.intercept('GET', '/api/stats', (req) => {
req.continue((res) => {
res.body.total = 0;
});
});
The first two examples do not touch the server: they are pure stubs. The third lets the request reach the server and changes only total, the other fields are real. For a JSON response res.body is already parsed into an object. All three routes for one URL are shown together here only for comparison; in one test the one registered last would win.
Limits and alternatives. A static response is faster and fully controlled but easily drifts from the real contract: the shape of the error body, field names, date formats. A response through req.continue stays closer to the real one but depends on the backend. delay simulates a delayed response, not real bandwidth: for that there is throttleKbps. To cut the connection use forceNetworkError: true. Take the fixture body from a real response or the API schema rather than inventing it.
And in Playwright:
Replacing is route.fulfill(), passing through is route.continue(), cutting is route.abort(). To change the real response use route.fetch() and fulfill with a new body.
A stubbed error with a body of a different shape than the real API: the UI test passes and in production the banner is not shown.
Calling req.reply() and then expecting the request to reach the server: after reply the response has already been given.
Changing res.body outside req.continue or a res callback: at that point there is no response yet.
Leaving delay in a shared beforeEach: every test gets slower for no reason.
Check yourself
What is the difference between req.reply() and req.continue(cb) for a request that exercises backend discount logic?
Answer
After req.reply() the server never sees the request, so the discount logic does not run: the test only checks how the UI reacts to an invented response. req.continue(cb) sends the request to the server, the real backend calculates the discount, and the callback can only adjust the response.
A test with the stub { statusCode: 500, body: { error: 'boom' } } is green, and in production a 500 shows an empty banner. What was missing from the test?
Answer
The stub body did not match the real error format (for example, the app reads message, not error). The body shape should come from the contract or a real response.
Related lessons: “What is cy.intercept and where exactly does the interception happen?”, “Why must an intercept be set before the action, and what happens if there are several on one URL?”, “Fixtures in Cypress vs Playwright”, “What timeouts does Cypress have and how do you override them?”.
In an interview.Junior: For simple cases I pass the response as the third argument: a fixture, a status, a delay. That is how I check how the UI behaves on a 500 or a slow network. Middle/Senior: If I need to change a real response precisely, I write a handler with req.continue: the server works and I change one field. I take the shape of the error body from the contract so the stub does not drift from reality.
Why must an intercept be set before the action, and what happens if there are several on one URL?
A route acts only on requests that started after it was registered, so it is set before cy.visit or the click. When several routes match, Cypress goes from the newest, and a route that responds ends the search, so a later one overrides an earlier one. The times: 1 option removes a route after one match, which gives the failure-then-success scenario. All routes are reset before every test.
Cypress · Network
Two intercepts on one URL: which one answers, and how to make “first a failure, then success”?
A shared beforeEach sets a stub for /api/stats with a list, and one test must check the “Try again” button: the first request must fail, the second must pass. The test gets an error on every request or on none. The lesson explains when a route starts to act, how one of several is chosen and what the times option is for.
How it works and why. A route acts only on requests that started after it was registered. A request that has already gone will not be seen by it: if you register the route after cy.visit or a click, cy.wait times out, and this is a classic cause of flaky tests. When several routes match a request, Cypress goes through them from the newest to the oldest. A route with a response (a static response or req.reply) or with req.continue ends the search. A handler that only looks at the request passes it on. So a route registered later overrides an earlier one: that is how a test overrides the general stub from a shared beforeEach.
Which route answers
Figure 1. A newer route stands before an older one; times removes it after the needed number of matches.
Example: “first an error, then success”.
beforeEach(() => {
cy.intercept('GET', '/api/stats', {
fixture: 'stats.json',
}).as('stats');
});
it('the “Try again” button repeats the request', () => {
// a newer route: fires once and is dropped
cy.intercept(
{ method: 'GET', url: '/api/stats', times: 1 },
{ statusCode: 503 },
).as('statsFail');
cy.visit('/stats');
cy.wait('@statsFail');
cy.contains('Could not load');
cy.contains('button', 'Try again').click();
cy.wait('@stats');
cy.get('[data-cy=total]').should('be.visible');
});
The first request matches the newer route and gets a 503. After one match times: 1 removes it, and the second request reaches the route with the fixture. Without times every request would get a 503, because the newer route stands first.
Limits and alternatives. All routes are reset before every test, including those created in before(): in the second and later tests they are gone, so shared routes go in beforeEach. If the response depends on the request number, a counter in a handler can replace several routes, but it is harder to read than times. A chain of handlers that only change the request is handy for headers, when the final route answers itself.
And in Playwright:
The rules are similar: the route must be registered before the action, the last registered handler runs first, you can pass the request to the next one with route.fallback(), and the { times: 1 } option exists too.
Common mistakes.
Registering the route after cy.visit: the request slipped through and cy.wait timed out.
Creating a shared route in before(): in later tests it is gone.
Not adding times to the failure route: “Try again” can never succeed because every request gets a 503.
Expecting the older route to run first: the order is reversed, newest first.
Check yourself
A beforeEach sets a stub for /api/user with status 200, and the test later adds the same route with status 404 and no times. Which status does the page get?
Answer
404. The search goes from the newest route, it answers itself, and the older one with 200 does not act while the newer one exists.
A route is created in before(), the first test is green and the second fails on cy.wait. Why?
Answer
Cypress resets all routes before every test. In the first test the route is still there, in later ones it is gone, so the alias is empty. Create the route in beforeEach or in the test itself.
Related lessons: “What is cy.intercept and where exactly does the interception happen?”, “How do you wait for a request and check it through an alias?”, “How do you replace or change a server response?”, “What timeouts does Cypress have and how do you override them?”.
In an interview.Junior: A route sees only requests that happened after its registration, so I register it before visit or a click. If there are several routes on a URL, the last registered one runs first. Middle/Senior: I keep general stubs in beforeEach and override them in the test with what that test needs. For a “first a failure, then success” scenario I add times: 1 to the failure route. I remember that routes are reset before every test.
cy.intercept
cy.intercept has three parts: what to catch, what to do and what to call it with .as(). A route is matched by method and URL (string, glob or regex), or by an object with query or headers for the same URL. Without a response it is a spy, with a static response a stub, and a handler changes the request or response. It sees only page HTTP requests, not WebSocket or cy.request.
Cypress · Network
What call forms does cy.intercept have and when to take which: a string, an object, a handler?
In a project one test waits for a request, a second replaces a response, a third tells GraphQL requests apart, and each is written differently. This lesson gathers the call forms of cy.intercept so you can see which fits which task; each is covered in detail in the neighbouring lessons of the chapter.
How it works and why.cy.intercept has three parts: what to catch (method, URL, other conditions), what to do (nothing, a static response or a handler) and what to call it (.as()). That is enough to cover observing, stubbing and changing a request or a response with one tool. Conditions can be given as a string, a glob, a regular expression or an object, and the response or the handler goes in as the last argument: third after a method and a URL, second after an object.
Two ways to describe a match
String or glob
Quick and short
A method and a URL in one call: cy.intercept('GET', '/api/users*'). That is enough for most tests.
A RouteMatcher object
Finer conditions
Method, URL, query, headers and times in one object when the URL is the same but the requests differ.
Figure 1. Both ways are equal: an object is needed when a string is not enough.
All typical tasks in one table:
Task
Call
What happens
Wait for a request
cy.intercept(m, url).as('x')
a spy, the request goes to the server
Replace a response
cy.intercept(m, url, { fixture })
a stub, no server
Change a request
(req) => { req.headers[…] = … }
then goes to the server
Change a response
req.continue((res) => …)
the real response, edited
Tell requests apart
req.alias = 'x'
an alias in a handler (GraphQL)
Example: an object instead of a string.
// page 2 of the list, not any page
cy.intercept({
method: 'GET',
pathname: '/api/users',
query: { page: '2' },
}).as('usersPage2');
// GraphQL: one URL, different operations
cy.intercept('POST', '/graphql', (req) => {
if (req.body.operationName === 'Login') {
req.alias = 'login';
}
});
// a network failure
cy.intercept('GET', '/api/users', { forceNetworkError: true });
The first route catches only the second page of the list, because the URL is the same and the page parameter tells requests apart. The second only sets an alias in a handler and replaces nothing, so the request goes to the server. The third simulates a dropped connection.
Limits and alternatives. The route must be declared before the action, and cy.intercept itself sees only HTTP requests of the page (not WebSockets and not cy.request). It lets you test the UI apart from an unstable backend but does not confirm the backend itself: that needs API tests. When there are many tests, shared calls are moved into a custom command or beforeEach so routes are not copied.
And in Playwright:
One function page.route(url, handler) with the actions fulfill, continue, abort and fallback; for waiting for a request there are separate waitForRequest and waitForResponse.
Common mistakes.
Taking a string when the URL matches several requests: the stub answers the wrong request.
Forgetting .as() and then hunting for the request in the log instead of cy.wait.
Relying on a stub instead of checking the real backend: the contract may change and the test will not notice.
Check yourself
A user list is requested with ?page=1 and ?page=2 on one URL. How do you stub only the second page?
Answer
Pass an object instead of a string: { method: 'GET', pathname: '/api/users', query: { page: '2' } } with the response as the second argument. The first page then goes to the real server.
How do you tell two GraphQL requests apart when the URL and the method are the same?
Answer
Read req.body.operationName in a handler and set req.alias for the needed operation, then wait with cy.wait('@login').
Related lessons: “What is cy.intercept and where exactly does the interception happen?”, “How do you wait for a request and check it through an alias?”, “How do you replace or change a server response?”, “Why must an intercept be set before the action, and what happens if there are several on one URL?”.
In an interview.Junior:cy.intercept catches HTTP requests by method and URL. It is used to wait for a request, replace a response and check what was sent. Middle/Senior: For finer conditions I take an object with query, headers and times, and for GraphQL I set an alias in a handler. I simulate errors and a slow network through statusCode, delay and forceNetworkError. I keep part of the tests without mocks so the real backend is checked too.