Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk9 min

Testing Edge Cases With Cypress Network Stubbing and App Actions

A practical guide to Cypress network stubbing: register intercepts before app actions, wait for the matching request, reproduce difficult states, and keep real-server coverage where the client/server contract matters.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To test an edge case in Cypress, register a narrow cy.intercept() route before the UI action that triggers the request, assign it an alias, perform the action, and wait for that alias before asserting on the response and rendered state. This lets you reproduce conditions such as no results, server errors, or slow responses deterministically. A stub tests how the client handles the response you supplied; it does not prove that production returns that response contract.

How app actions and network interception work together

An app action—such as typing in a search box or submitting a form—can cause the browser application to send an HTTP request. cy.intercept() can observe that browser traffic, let it reach the server, or supply a controlled response instead. When the action, request, and assertion are connected in that order, the test can check both the network result and what the user sees.

As an Amazon Associate I earn from qualifying purchases.

  1. Register an intercept for the request the action is expected to make.
  2. Give it an alias with .as().
  3. Perform the UI action that should trigger the request.
  4. Wait for the alias with cy.wait().
  5. Assert on the request or response as needed, then assert on the visible interface.

For example, a search test can supply a deterministic empty result instead of depending on the current contents or availability of a live database:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
it('shows an empty state when search returns no results', () => {
  cy.intercept('GET', '**/api/search?q=unmatched', {
    statusCode: 200,
    body: { results: [] },
  }).as('search');

  cy.visit('/search');
  cy.get('[data-cy=search]').type('unmatched');

  cy.wait('@search').then(({ request, response }) => {
    expect(request.method).to.equal('GET');
    expect(response.statusCode).to.equal(200);
    expect(response.body.results).to.deep.equal([]);
  });

  cy.contains('No results').should('be.visible');
});

Adjust the URL pattern, selector, response shape, and expected message to your application. The route must match the request the app actually makes; if it does not, Cypress will wait without seeing the expected alias.

Choose stubs or real responses based on the question

Approach What it exercises well What it does not establish Useful when
Stubbed response with cy.intercept() Client handling of a known status, body, headers, or delay; repeatable reproduction of rare states. Whether the real server returns the same response or honors the same contract. You need controlled no-result, error, malformed/unusual payload, or delayed-response cases.
Real application response The integrated client/server path and the contract used by that test. Reliable reproduction of rare states unless test data and server conditions are arranged. You want confidence in a critical path using the actual service.

Cypress says its Real World App end-to-end tests predominantly rely on server responses and stub only on a few occasions to create edge or hard-to-create states (Cypress: Intercepting network requests in Cypress). A balanced suite can keep a meaningful real-response test for critical behavior and use stubs for conditions that are difficult, costly, or unstable to arrange. Real responses may require seeded data and can take longer; stubs are fast and controllable but cover only the client response path you have supplied. Cypress likewise cautions that a stubbed response need not match actual server data (Cypress: Effective E2E testing in Cypress).

Stub useful edge cases without relying on arbitrary sleeps

The route handler can control the response body, status code, headers, and delay. Build the response around the UI behavior under test, and assert on the resulting state rather than treating the stub itself as proof that the interface works.

Empty or unusual data

Return an empty collection or an unusual but intentional payload to verify that the app handles the boundary correctly. Keep the body shape explicit so the test documents what the client is expected to handle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.intercept('GET', '**/api/items', {
  statusCode: 200,
  body: { items: [] },
}).as('items');

cy.get('[data-cy=refresh]').click();
cy.wait('@items');
cy.contains('No items found').should('be.visible');

Server error state

Supply a 4xx or 5xx response to test the app’s error handling. Cypress’s FAQ discusses testing endpoints that return these status classes; in an application test, verify the user-facing error or recovery behavior that matters (Cypress: Frequently asked questions: Cypress App).

cy.intercept('POST', '**/api/orders', {
  statusCode: 500,
  body: { message: 'Unable to create order' },
}).as('createOrder');

cy.get('[data-cy=submit-order]').click();
cy.wait('@createOrder').its('response.statusCode').should('equal', 500);
cy.contains('Unable to create order').should('be.visible');

Delayed response

A delay in the stub can exercise a loading indicator or disabled control. Wait for the request alias and check the intermediate UI state while the response is still pending; avoid replacing request synchronization with a fixed sleep.

cy.intercept('GET', '**/api/profile', {
  statusCode: 200,
  body: { name: 'Ada' },
  delay: 800,
}).as('profile');

cy.visit('/profile');
cy.get('[data-cy=loading]').should('be.visible');
cy.wait('@profile');
cy.contains('Ada').should('be.visible');

The Cypress network guide notes that most stubbed responses return in less than 20 ms; this is vendor guidance, not a general timing guarantee. Use a deliberate delay only when testing behavior that depends on a response taking time (Cypress: Intercepting network requests in Cypress).

Wait for the request that caused the state change

Register the intercept before the action. If the app sends its request before the route is registered, Cypress cannot observe that earlier request through the intercept. Waiting on a named request synchronizes the test with the event under test and helps separate a request failure from a rendering failure.

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

cy.wait('@alias') yields the intercepted exchange, including request and response details when available. Use those details to diagnose whether the right method and URL were sent and whether the expected response reached the app. Then assert on the visible result, since a correct network response alone does not show that the UI rendered it correctly. Cypress recommends waiting for requests rather than using arbitrary fixed delays (Cypress: Intercepting network requests in Cypress).

Use cy.intercept() for app traffic and cy.request() for direct API calls

cy.intercept() applies to HTTP requests made by the browser application. cy.request() makes a direct API call from Cypress’s Node process; that call is not browser app traffic, so an intercept will not spy on or stub it. Use the command that matches the layer you intend to test (Cypress: cy.intercept() API reference; Cypress: Frequently asked questions: Cypress App).

  • Use cy.intercept() when driving the interface and controlling or observing the app’s request.
  • Use cy.request() when calling an endpoint directly and inspecting its response.
  • A hybrid test can perform a UI action, then make a direct request to verify persisted state; keep clear which part covers the browser path and which part checks the API.

Route matching, ordering, caching, and WebSockets

Keep route matching narrow

Match the method and the endpoint needed for the test rather than catching every request with a wildcard. Cypress notes that intercepting broad traffic adds handling overhead because each matching request passes through intercept handling (Cypress: Optimizing test performance). If multiple routes could match, remember that ordinary matching routes are considered in reverse definition order; middleware routes run first. Intercepts are cleared before each test, so register the routes each test needs (Cypress: cy.intercept() API reference).

Account for browser cache

A browser-cached resource may not generate a network request, leaving no request for cy.intercept() to observe. Cypress’s native interception documentation also says that, starting with Cypress 16, responses handled internally by Cypress are not stored in the browser HTTP cache, so a later navigation can reach the intercept again (Cypress: Native network interception in Cypress). Distinguish a cache hit from a route-matching or timing problem when an expected intercept does not fire.

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.

WebSocket messages are a different case

cy.intercept() does not natively stub individual WebSocket frames or messages. The Cypress network guide recommends alternatives such as controlling application callbacks, coordinating the desired messages through the server, or using a helper WebSocket client (Cypress: Intercepting network requests in Cypress).

Check Cypress version and browser before asserting on network details

Native interception behavior is version- and browser-specific. Cypress documents that beginning with Cypress 16, Chrome, Chromium, and Edge intercept test traffic on the native browser network. The same documentation describes behavior changes involving cache and response observation. In particular, browser-rejected responses may not be observable in the same way, and some request or response properties documented for older setups may not be reported in Chrome, Chromium, or Edge (Cypress: Native network interception in Cypress; Cypress: cy.intercept() API reference).

Check the project’s installed Cypress version and browser matrix before making assertions on transport metadata. For browser-rejected responses, focus on the application’s error state rather than assuming every low-level response detail will be available. The Cypress guidance cited here does not establish a geographic variation for this technique.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot a request that does not behave as expected

Symptom Likely cause What to check or change
cy.wait('@alias') times out The route was registered after the action, its matcher does not fit the actual request, or the resource came from cache. Register before the action; verify the actual method and URL; account for browser caching.
The app still receives a live response The route matcher did not match the request, or another matching route affected handling. Narrowly inspect method and URL patterns, then review route definition order and middleware use.
A cy.request() call is not intercepted cy.request() runs from Cypress’s Node process, not as a browser request from the app. Use cy.intercept() for browser app traffic; inspect direct calls through the cy.request() result.
A request assertion fails only in a newer browser setup Native interception may expose different response or transport details, or the browser may reject the response. Confirm Cypress version and browser; assert on application behavior when transport metadata is unavailable.
A WebSocket message is not stubbed cy.intercept() handles HTTP traffic, not individual WebSocket frames or messages. Control callbacks, coordinate messages through the server, or use a helper WebSocket client.
The UI assertion fails after the alias resolves The request completed, but the app may not have rendered the state as expected, or the stub body may not match what the client handles. Inspect the yielded response and assert separately on the relevant visible UI state.

Or skip the browser setup

If the task is to capture a website screenshot rather than test an app’s network behavior, ScreenshotNeo offers a one-request screenshot API and an MCP server. It is not a substitute for Cypress network tests: use it for screenshots, not to establish client/server test coverage.

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

For a clean screenshot of a page, the cURL request below returns a WebP file; see the ScreenshotNeo documentation for API 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 are accepted before capture, and more than 60 known consent platforms, newsletter popups, and chat widgets can be removed; each step can be turned off.
  • Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

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

Frequently Asked Questions

Can cy.intercept() prove that the production API returns the stubbed response?

No. It proves how the client behaves for the response supplied by the test. A real-server test is needed to exercise the actual client/server response contract.

Why can a browser-cached request be invisible to cy.intercept()?

A cached resource may not trigger a network request for Cypress to observe. Cypress 16 native interception also changes how internally handled responses interact with the browser HTTP cache; see the version-specific guidance linked above.

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

Can cy.intercept() stub individual WebSocket messages?

No. Cypress recommends controlling callbacks, coordinating messages through the server, or using a helper WebSocket client for that case.

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 *

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.