| | |

Cypress 12 ๐ŸŒฒ Network Interception โ€” cy.intercept and Stubbing API Responses

โฑ๏ธ Estimated read: 10 min | |

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

FormExample
Method + pathcy.intercept("GET", "/api/users", ...)
Path onlycy.intercept("/api/users", ...)
Globcy.intercept("GET", "/api/users/*", ...)
Regexcy.intercept(/\/api\/users\/\d+/, ...)

Handler Forms

HandlerBehavior
Static objectStub the response
(req) => req.reply(...)Dynamic stub
(req) => req.continue(...)Pass through
(req) => req.abort()Fail the request
No handlerSpy

Response Options

OptionEffect
fixtureLoad from fixtures
statusCodeSet the status
bodySet the body
delaySimulate latency
forceNetworkErrorSimulate 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

PitfallWhy It HappensFix
Test passes locally, fails in CINo cy.waitWait on the alias
Stub not appliedIntercept registered after the visitRegister before cy.visit
Real request hits the serverNo handler on the interceptAdd a stub handler
Loading state not visibleResponse too fastAdd 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

ItemValue
Commandcy.intercept(method, url, handler)
SpyNo handler, pass through
StubHandler with a reply
Alias.as("name")
Waitcy.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.wait is 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 delay makes the loading state visible, and a forceNetworkError makes 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.

Was this helpful?


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!