October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Stub Network Requests with cy.intercept() in Cypress

A practical guide to Cypress cy.intercept() stubs, route matching, fixtures, dynamic handlers, waits, assertions, and choosing when to use the real backend.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Register cy.intercept() before the request happens, match the request you want, and provide a static response or handler. Give the route an alias, trigger the request, then use cy.wait('@alias') to inspect the request and response. For requests made as the page starts up, install the intercept before cy.visit().

Stub a request with a static response

This example returns predictable user data for a GET request. The method, URL, response body, alias, and wait all work together:

As an Amazon Associate I earn from qualifying purchases.

cy.intercept('GET', '/api/users', {
  statusCode: 200,
  body: [{ id: 1, name: 'Ada' }],
}).as('getUsers')

cy.visit('/users')
cy.wait('@getUsers')
  .its('response.statusCode')
  .should('eq', 200)

Place the intercept before the action that triggers the request. If the application fetches users during initialization, register the route before cy.visit(), as above. Cypress clears intercepts before each test, so define them in every test that needs them or in suitable test setup. Cypress API documentation

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose what the intercept matches

Match a specific method and URL

For one known endpoint, use an exact URL and method. If you omit the method, Cypress matches all HTTP methods by default; specifying it avoids catching unrelated traffic.

cy.intercept('GET', '/api/users', {
  statusCode: 200,
  body: [{ id: 1, name: 'Ada' }],
}).as('getUsers')

Match query strings or variable URLs

When the application adds query parameters or identifiers, use a glob, regular expression, or RouteMatcher. Route matcher strings follow Cypress minimatch behavior. All fields supplied to a RouteMatcher must match.

cy.intercept({
  method: 'GET',
  pathname: '/api/users',
  query: { active: 'true' },
}, { fixture: 'active-users.json' }).as('activeUsers')

Other matcher fields include hostname, path, headers, and additional request constraints. Use only the fields that reflect the request your test intends to catch. RouteMatcher reference

Return fixture data or configure a static response

Use a fixture

For a stable response stored with the test, refer to the fixture in the intercept:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers')

Fixtures make test input explicit and reusable. For binary files such as PDFs or MP4s where the exact bytes matter, Cypress warns that the default UTF-8 handling may be unsuitable. Specify null encoding in the fixture reference, for example fixture: 'media/file.pdf,null'. Cypress fixture documentation

Set response behavior

A StaticResponse can set a response body, status code, headers, fixture, delay, throttle rate, or a forced network error. Choose the smallest response configuration that represents the condition under test; a forced error or delay is useful when the test specifically covers those states.

Use a handler for request-dependent behavior

A route handler is useful when the response depends on the outgoing request, or when the test needs to inspect or change that request. Use req.reply() to end the request with a stubbed response, or req.continue() to forward it to the destination, optionally handling the response.

cy.intercept('POST', '/api/users', (req) => {
  expect(req.body).to.have.property('name')
  req.reply({ statusCode: 201, body: { id: 42, ...req.body } })
}).as('createUser')

Matching routes are processed in reverse definition order, except middleware routes, which run first. Calling req.reply() ends the request phase and prevents propagation to later matching handlers. Keep route order and termination behavior in mind if multiple intercepts can match the same request. Handler and route-order details

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait for the request and assert on its result

cy.intercept() itself yields null; it does not yield the intercepted request. Alias the route and wait for it after the action that should make the request. cy.wait('@alias') yields an interception object with request and response details.

cy.get('button').contains('Save').click()
cy.wait('@createUser').then(({ request, response }) => {
  expect(request.body).to.have.property('name')
  expect(response.statusCode).to.eq(201)
})

Assert on meaningful behavior such as request.body, response.statusCode, or response.body. Waiting on the alias synchronizes the test with the matching request-response cycle instead of relying on an arbitrary fixed sleep. Cypress also documents waiting for intercepted requests that finish with a network error. Waiting and interception object reference

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Choose between a stub and the real backend

Stub when the test needs deterministic data or an edge state that is inconvenient to create through the application. Use the real backend when the test must exercise integrated behavior or backend logic. Cypress supports both approaches, and they can be mixed across a suite.

Consideration Stubbed response Real backend
Determinism Response is controlled by the test. Depends on backend state and behavior.
Backend coverage Does not exercise the destination service for the stubbed request. Exercises the server response and integrated behavior.
Creating a specific state Can directly supply the desired response or edge case. May require seeded test data and adherence to application business logic.
Maintenance Requires maintaining fixtures or handler logic that represents expected data. May require maintaining data-seeding scripts and backend test setup.

Cypress’s Real World App end-to-end tests predominantly use server responses and stub only on a few occasions for convenient edge cases. That is a useful distinction: stubbing is a control for targeted test cases, not a substitute for every test that should verify the integrated application. Cypress network requests guide

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot common intercept problems

  • The request is not captured: register the intercept before the request. For initialization traffic, add it before cy.visit(); also verify that the method and URL or matcher fields match the actual request.
  • The route catches unexpected traffic: add an explicit HTTP method, since omitting it matches all methods, and narrow the URL or matcher fields.
  • cy.intercept() appears to return no request: that command yields null. Add an alias and inspect the cycle with cy.wait('@alias').
  • A binary fixture is corrupted or not served as expected: for supported binary cases such as PDF or MP4, use the null encoding suffix, for example media/file.pdf,null.
  • A later handler does not run: check whether an earlier matching route called req.reply(), which ends the request phase, and account for reverse definition order and middleware routes.
  • A stub persists only in some tests: Cypress clears intercepts before each test. Register required routes again in each test or its appropriate setup.
  • A test passes with a stub but misses a backend defect: add or retain tests that reach the real server for behavior the stubbed test cannot validate.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your task is to capture a website screenshot rather than test application network behavior, ScreenshotNeo provides a screenshot API and MCP server. A single GET request can return an image or PDF; see the API documentation for options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; responses include X-Page-Verdict and X-Billed headers.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo and get 1,000 screenshots a month free, with no card required.

Frequently Asked Questions

Does cy.intercept() work for requests made during page initialization?

Yes. Register the intercept before calling cy.visit() so it is in place before initialization requests fire.

Can cy.wait() observe a request that ends in a network error?

Yes. Cypress documents waiting for intercepted requests that end in a network error; inspect the yielded interception for the outcome.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.