Cypress 12 ๐ฒ Network Interception โ cy.intercept and Stubbing API Responses
cy.intercept() is Cypress’s network layer. It watches the requests the application makes, and it can stub the response, modify the request, or simply wait for the request to complete. The command replaced cy.route() in Cypress 6 and it runs in the Node proxy, which means it sees the requests the application makes at the network level, not just the ones the test dispatches. The two uses that matter are the stubโa deterministic response for a test that should not depend on the real APIโand the waitโa synchronization point for a test that needs the network to settle before the assertion.
This chapter covers the cy.intercept() matcher, the stub and the spy forms, and the alias that turns an intercept into a wait. The sections that follow walk through the route matcher, the reply/continue/abort behaviors, and the cy.wait("@alias") pattern that replaces the hard-coded wait.
Key point: cy.intercept(method, url, handler) matches a request and either stubs the response, passes it through, or aborts it; the .as("alias") call lets cy.wait("@alias") block until the request completes, and the cy.wait response object carries the request and response bodies for the assertion.
a. The matcher and the handler
The cy.intercept() signature is (method, url, handler) or (url, handler). The URL is a string, a glob, or a regex. The handler is either a static response object or a function that receives the req and returns a response, or calls req.reply, req.continue, or req.abort.
// Match a GET to the users endpoint
cy.intercept("GET", "/api/users", { fixture: "users.json" });
// Match any method
cy.intercept("/api/users", { statusCode: 200, body: [] });
// Match with a glob
cy.intercept("GET", "/api/users/*", { fixture: "user.json" });
// Match with a regex
cy.intercept(/\/api\/users\/\d+/, { fixture: "user.json" });
The static response is the shortest form. The { fixture: "users.json" } object reads the fixture from cypress/fixtures/users.json, which is the pattern for a response that the test needs to control but does not need to compute. The { statusCode, body, headers } form is the explicit response, and the { forceNetworkError: true } form simulates a network failure.
The function handler is the dynamic form. It receives the req object, and it can read the request body, the URL, and the headers before deciding what to reply.
cy.intercept("POST", "/api/users", (req) => {
req.reply({
statusCode: 201,
body: { id: "1", ...req.body },
});
});
The req.reply() sends a stubbed response, req.continue() passes the request to the real server (with an optional modification), and req.abort() fails the request. The req.alias property is the way to alias the intercept from inside the handler, which is the pattern for a dynamic matcher.
b. The spy, the stub, and the alias
An intercept without a handler is a spy: it lets the request through to the real server and records it. The .as("alias") call names the intercept, and cy.wait("@alias") waits for the request to complete.
// Spy: the request reaches the real server
cy.intercept("GET", "/api/users").as("getUsers");
cy.visit("/users");
cy.wait("@getUsers").its("response.statusCode").should("eq", 200);
The cy.wait("@getUsers") yields an object with request and response properties. The request has the URL, method, headers, and body the application sent; the response has the status code, headers, and body the server returned. The its("response.body") chain is the way to assert on the response body without a separate variable.
The stub is the intercept with a handler that does not call req.continue(). The request never reaches the real server, and the response is whatever the handler replies with.
// Stub: the request is answered by the intercept
cy.intercept("GET", "/api/users", { fixture: "users.json" }).as("getUsers");
cy.visit("/users");
cy.wait("@getUsers");
cy.get("li").should("have.length", 3);
The difference between the spy and the stub is the presence of the handler. The spy is for a test that needs the real backend and wants to wait for the request; the stub is for a test that needs a deterministic response and does not want the backend to be involved.
The cy.wait("@alias") is the synchronization point. It is the replacement for the hard-coded cy.wait(2000) that guesses how long the request takes, and it is the assertion that the request was actually made. A test that stubs a response and asserts on the UI without the cy.wait is a test that passes on a fast machine and fails on a slow one, because the assertion runs before the response is applied.
c. The request modification and the intercept ordering
req.continue() with a callback is the form for modifying the request before it reaches the server. The callback receives the res object, and it can change the response body, the headers, or the status.
cy.intercept("GET", "/api/users", (req) => {
req.continue((res) => {
res.body.push({ id: "99", name: "Injected" });
});
});
The req.headers object can be modified before the req.continue() call, which is the pattern for injecting an auth token into every request. The req.reply() with a delay simulates a slow response, which is the pattern for a loading-state test.
cy.intercept("GET", "/api/users", (req) => {
req.reply({ fixture: "users.json", delay: 1000 });
});
The intercepts are matched in reverse order of registration. A cy.intercept registered later takes precedence over an earlier one for the same URL, which is the mechanism for overriding a global stub in a single test. The global stub is registered in a beforeEach, and the test registers a more specific intercept for the one call it needs to change.
beforeEach(() => {
cy.intercept("GET", "/api/**", { fixture: "default.json" });
});
it("overrides the stub", () => {
cy.intercept("GET", "/api/users", { fixture: "users.json" });
// the users call uses users.json, the rest use default.json
});
The cy.intercept with a times option limits the number of matches. A stub with times: 1 responds once and lets the subsequent requests through to the real server, which is the pattern for the “first call fails, retry succeeds” test.
Complete Example Session
// ============================================
// PART 1: THE SPY
// ============================================
describe("spy", () => {
it("waits for the real request", () => {
cy.intercept("GET", "/api/users").as("getUsers");
cy.visit("/users");
cy.wait("@getUsers").its("response.statusCode").should("eq", 200);
cy.get("li").should("have.length", 3);
});
});
// ============================================
// PART 2: THE STUB
// ============================================
describe("stub", () => {
it("uses a fixture", () => {
cy.intercept("GET", "/api/users", { fixture: "users.json" }).as("getUsers");
cy.visit("/users");
cy.wait("@getUsers");
cy.get("li").should("have.length", 3);
});
});
// ============================================
// PART 3: THE DYNAMIC REPLY
// ============================================
describe("dynamic", () => {
it("replies based on the request", () => {
cy.intercept("POST", "/api/users", (req) => {
req.reply({ statusCode: 201, body: { id: "1", ...req.body } });
}).as("createUser");
cy.visit("/users/new");
cy.get('[data-cy="name"]').type("Ana");
cy.get('[data-cy="submit"]').click();
cy.wait("@createUser").its("request.body.name").should("eq", "Ana");
});
});
// ============================================
// PART 4: THE ERROR AND THE DELAY
// ============================================
describe("edge cases", () => {
it("shows the error state", () => {
cy.intercept("GET", "/api/users", { forceNetworkError: true });
cy.visit("/users");
cy.get('[data-cy="error"]').should("be.visible");
});
it("shows the loading state", () => {
cy.intercept("GET", "/api/users", { fixture: "users.json", delay: 1000 });
cy.visit("/users");
cy.get('[data-cy="spinner"]').should("be.visible");
});
});
The parts covered the spy, the stub, the dynamic reply, and the error and delay cases.
Quick Reference
Matcher Forms
| Form | Example |
|---|---|
| Method + path | cy.intercept("GET", "/api/users", ...) |
| Path only | cy.intercept("/api/users", ...) |
| Glob | cy.intercept("GET", "/api/users/*", ...) |
| Regex | cy.intercept(/\/api\/users\/\d+/, ...) |
Handler Forms
| Handler | Behavior |
|---|---|
| Static object | Stub the response |
(req) => req.reply(...) | Dynamic stub |
(req) => req.continue(...) | Pass through |
(req) => req.abort() | Fail the request |
| No handler | Spy |
Response Options
| Option | Effect |
|---|---|
fixture | Load from fixtures |
statusCode | Set the status |
body | Set the body |
delay | Simulate latency |
forceNetworkError | Simulate failure |
Best Practices
โ Do This:
// Alias the intercept and wait for it
cy.intercept("GET", "/api/users").as("getUsers");
cy.wait("@getUsers"); // โ
// Stub for deterministic tests
cy.intercept("GET", "/api/users", { fixture: "users.json" }); // โ
// Use delay for loading-state tests
cy.intercept("GET", "/api/users", { fixture: "users.json", delay: 1000 }); // โ
โ Don’t Do This:
// Hard-coded wait
cy.wait(2000); // use cy.wait("@alias") // โ
// Stub without waiting
cy.intercept("GET", "/api/users", { fixture: "users.json" });
// no cy.wait โ the assertion may run before the response // โ
// Spy without an alias
cy.intercept("GET", "/api/users"); // cannot wait for it // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Test passes locally, fails in CI | No cy.wait | Wait on the alias |
| Stub not applied | Intercept registered after the visit | Register before cy.visit |
| Real request hits the server | No handler on the intercept | Add a stub handler |
| Loading state not visible | Response too fast | Add delay |
Real-World Examples
1. Spy
cy.intercept("GET", "/api/users").as("getUsers");
2. Stub with fixture
cy.intercept("GET", "/api/users", { fixture: "users.json" });
3. Dynamic reply
cy.intercept("POST", "/api/users", (req) => req.reply({ statusCode: 201, body: req.body }));
4. Pass through
cy.intercept("GET", "/api/users", (req) => req.continue());
5. Abort
cy.intercept("GET", "/api/users", (req) => req.abort());
6. Network error
cy.intercept("GET", "/api/users", { forceNetworkError: true });
7. Delay
cy.intercept("GET", "/api/users", { fixture: "users.json", delay: 1000 });
8. Wait and assert
cy.wait("@getUsers").its("response.body").should("have.length", 3);
9. Request assertion
cy.wait("@createUser").its("request.body.name").should("eq", "Ana");
10. Override in a test
beforeEach(() => { cy.intercept("GET", "/api/**", { fixture: "default.json" }); });
Visual
The Intercept Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ App makes a request โ
โ โ โ
โ โผ โ
โ cy.intercept matches the URL โ
โ โ โ
โ โโโโโโดโโโโโ โ
โ โผ โผ โ
โ handler no handler โ
โ โ โ โ
โ โผ โผ โ
โ reply/ pass through โ
โ continue (spy) โ
โ /abort โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Spy vs Stub
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SPY โ
โ cy.intercept("GET", "/api/users").as("getUsers") โ
โ โ request reaches the server โ
โ โ cy.wait("@getUsers") waits for it โ
โ โ
โ STUB โ
โ cy.intercept("GET", "/api/users", { fixture: "u.json" })โ
โ โ request is answered by the intercept โ
โ โ the server never sees it โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Wait
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.intercept("GET", "/api/users").as("getUsers"); โ
โ cy.visit("/users"); โ
โ cy.wait("@getUsers"); โโโ blocks until the request โ
โ cy.get("li").should("have.length", 3); โ
โ โ
โ Without the wait, the assertion races the response. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Delay
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.intercept("GET", "/api/users", { โ
โ fixture: "users.json", โ
โ delay: 1000, โ
โ }); โ
โ โ โ
โ โผ โ
โ The response arrives after 1s โ the spinner is visible โ
โ for the assertion. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Command | cy.intercept(method, url, handler) |
| Spy | No handler, pass through |
| Stub | Handler with a reply |
| Alias | .as("name") |
| Wait | cy.wait("@name") |
| Fixture | { fixture: "file.json" } |
| Delay | { delay: 1000 } |
| Network error | { forceNetworkError: true } |
Key takeaways:
cy.intercept()is the network layer. It matches a request by method and URL, and the handler either stubs the response, passes the request through, or aborts it. The intercept runs in the Node proxy, so it sees the requests the application makes at the network level.- The spy and the stub differ by the handler. A spy has no handler and lets the request reach the real server; a stub has a handler that replies. The spy is for the test that needs the real backend, and the stub is for the test that needs a deterministic response.
- The alias plus
cy.waitis the synchronization point.cy.wait("@alias")blocks until the request completes and yields the request and response objects, which is the replacement for the hard-coded wait. - The delay and the network error simulate the edge cases. A
delaymakes the loading state visible, and aforceNetworkErrormakes the error state reachable without breaking the real server. - The intercepts match in reverse registration order. A test-specific intercept overrides the global stub registered in a
beforeEach, which is the pattern for the one call that needs a different response.
Remember: cy.intercept is how a Cypress test controls the network. The spy waits for the real request, the stub answers with a fixture, and the alias plus cy.wait sequences the assertion after the response. Register the intercept before the cy.visit that triggers the request, alias it, and wait for it. A stub without a wait is a race, and a wait without an alias is the hard-coded delay that the intercept was meant to replace.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!