Resource library

QA Interview

Cypress Network Interception Interview Questions for Testers (2026)

Practice Cypress network interception interview questions with precise answers, runnable cy.intercept examples, debugging tactics, and senior-level trade-offs.

23 min read | 3,837 words

TL;DR

Strong answers explain when to spy, when to stub, how RouteMatcher works, and how cy.wait yields a request-response interception. They also acknowledge registration timing, cache, GraphQL operation matching, handler ordering, and the risk of over-mocking.

Key Takeaways

  • Register cy.intercept before the application sends the request you need to observe.
  • Use aliases and cy.wait to synchronize on meaningful network events instead of arbitrary delays.
  • Choose spying for integration confidence and stubbing for deterministic UI scenarios.
  • Match narrowly with method, pathname, query, headers, or times to avoid catching unrelated traffic.
  • Assert the yielded interception object to diagnose request, response, and routing behavior.
  • Explain middleware ordering, request continuation, response control, and cache limitations in senior interviews.

Cypress network interception interview questions test more than whether you remember cy.intercept(). Interviewers want evidence that you can observe browser traffic, control responses without hiding defects, synchronize tests deterministically, and diagnose failures from the interception object.

This guide gives concise model answers plus runnable examples for modern Cypress E2E tests. Use it to rehearse the reasoning behind each API choice, then apply the same patterns in a small project or the Cypress cy.intercept guide.

TL;DR

Topic Interview-ready point
Spy Omit a response handler to observe the real request and response
Stub Supply a StaticResponse or route handler to control the reply
Match Combine method and URL properties so unrelated calls do not match
Wait Alias the route, then inspect the interception yielded by cy.wait()
Modify Change req before req.continue(), or use req.reply() to end routing
Confidence Keep contract and end-to-end coverage because a stub can drift from production

The following Cypress network interception interview questions progress from fundamentals to senior debugging and architecture decisions.

1. Cypress Network Interception Interview Questions: Fundamentals

Q: What does cy.intercept() do?

cy.intercept() registers a route that can observe or alter HTTP requests made by the application under test. With no response argument, it behaves as a spy and lets the request reach the real server. With a static response or callback, it can stub, delay, redirect, destroy, or conditionally continue that traffic. It operates on browser-layer requests, so it is useful for UI behavior driven by REST, GraphQL, documents, scripts, and other HTTP resources.

Q: How is cy.intercept() different from the removed cy.route() API?

cy.route() belonged to the older cy.server() workflow and primarily instrumented XMLHttpRequest. cy.intercept() needs no cy.server(), handles fetch as well as XHR, supports richer matchers, and exposes request and response lifecycle controls. A current answer should use cy.intercept() because old examples built around cy.route() no longer represent a maintainable Cypress suite.

Q: Is cy.intercept() itself a network request?

No. It configures Cypress routing behavior and yields null; it does not send traffic. The application action, such as cy.visit() or a button click, causes the matching request. To make an API call directly from the test, use cy.request(), whose purpose and execution context differ from interception.

Q: What is the difference between spying and stubbing?

A spy observes a real exchange, which preserves backend integration but depends on server data and availability. A stub supplies a controlled response, which makes rare, slow, or destructive UI states reproducible. Good suites use both deliberately: a few real-service paths establish integration confidence, while focused UI tests stub boundary conditions such as 429, 500, empty results, and delayed success.

2. Matching Requests Precisely

Q: What forms can the first argument to cy.intercept() take?

It can be a URL string, a glob string, a regular expression, or a RouteMatcher object. The object supports properties such as method, url, hostname, path, pathname, query, headers, auth, https, port, times, and middleware. Use the smallest readable combination that uniquely identifies the intended request rather than a broad wildcard that silently captures several endpoints.

Q: Why specify the HTTP method?

A pathname can serve different operations under GET, POST, PUT, PATCH, or DELETE. Omitting method matches every method, so a broad interceptor might accidentally stub a write while you intended only to observe a read. Explicit method matching documents intent and prevents misleading passes when an application changes its request verb.

Q: How do glob patterns work in URL matching?

Cypress uses minimatch-style glob matching with matchBase: true. A pattern such as **/api/users/* can cover any origin followed by one user identifier, while **/api/users/** covers deeper descendants too. Prefer pathname when query order or host variability should not affect the match, and test the pattern against the actual browser request if an alias never resolves.

Q: When should you match query parameters with RouteMatcher?

Use the query property when a parameter changes server behavior and therefore defines the scenario, such as pagination, filters, or search text. Object matching is clearer than encoding every parameter in a URL string and avoids depending on query ordering. Match only relevant keys so harmless analytics or cache-busting parameters do not make the test brittle.

// cypress/e2e/search.cy.js
describe('search interception', () => {
  it('matches the request by method, pathname, and query', () => {
    cy.intercept({
      method: 'GET',
      pathname: '/api/search',
      query: { q: 'cypress', page: '1' }
    }, {
      statusCode: 200,
      body: { items: [{ id: 1, title: 'Network testing' }] }
    }).as('search')

    cy.visit('/search?q=cypress')
    cy.wait('@search').its('response.statusCode').should('eq', 200)
    cy.contains('Network testing').should('be.visible')
  })
})

Run npx cypress run --spec cypress/e2e/search.cy.js. The verification is both the 200 assertion and the visible result; if the matcher is wrong, cy.wait('@search') times out.

3. Aliases, Waiting, and Assertions

Q: Why alias an intercepted route?

An alias gives a semantic name to a registered route and lets the command queue wait for a specific matching cycle. cy.wait('@getUsers') resolves only after Cypress sees the request and its response, which is more meaningful than sleeping for a fixed duration. The yielded object also creates one place to assert outgoing data, incoming data, status, and headers.

Q: What does cy.wait('@alias') yield?

It yields an interception containing an id, request, and usually a response. The request includes fields such as method, URL, headers, and body; the response includes status code, headers, body, and duration-related data when available. If the route is forcefully destroyed, inspect the error property instead of expecting a normal response.

Q: Can Cypress wait for the same alias multiple times?

Yes. Each cy.wait('@poll') consumes the next matching occurrence in sequence. This makes repeated calls explicit, but the test must know why another request should occur, perhaps a refresh action or retry policy. When the count itself matters, increment a variable inside the handler and assert it after the triggering behavior finishes.

Q: How do you assert request and response data safely?

Wait on the alias and use .then() when several related assertions need local variables. Assert stable contract fields, not incidental headers injected by a proxy or browser. For request bodies, verify business-critical values and types; for responses, verify the status and the subset the UI depends on, leaving exhaustive schema validation to a contract-testing layer.

cy.intercept('POST', '/api/orders').as('createOrder')
cy.get('[data-cy=submit-order]').click()
cy.wait('@createOrder').then(({ request, response }) => {
  expect(request.body).to.include({ currency: 'USD' })
  expect(request.body.items).to.have.length.greaterThan(0)
  expect(response.statusCode).to.eq(201)
  expect(response.body).to.have.property('id')
})

4. Cypress Network Interception Interview Questions About Stubbing

Q: How do you return a static response?

Pass a StaticResponse as the final argument. It may contain statusCode, body, headers, fixture, delay, throttleKbps, or forceNetworkError. Keep the stub shaped like the production contract, and make the UI assertion prove that the application consumed it rather than merely proving the interceptor returned it.

Q: How do you use a fixture in an interceptor?

Set the fixture property in a static response, for example { fixture: 'users.json' }. Cypress loads the file from the configured fixtures folder and serves it as the response body. Fixtures are useful for substantial reusable payloads, but small scenario-specific bodies are often easier to read inline and less likely to become a shared mutable dumping ground.

Q: How do you simulate a server error?

Return the exact status and payload the application contract defines for that failure. A 500 response tests server-error rendering, while a 401, 403, 404, 409, or 429 exercises materially different product behavior. Assert the user-facing recovery path, such as retry, reauthentication, conflict guidance, or rate-limit messaging, rather than only checking the status in the interception.

Q: How do you simulate a network failure rather than an HTTP failure?

Use { forceNetworkError: true } as the static response. This represents a connection-level failure with no HTTP status, so it should drive offline or generic connectivity handling. Do not call a 500 a network error: the server produced a valid HTTP response in that case, and applications commonly treat the two conditions differently.

describe('profile resilience', () => {
  it('offers retry after a connection failure', () => {
    cy.intercept({ method: 'GET', pathname: '/api/profile', times: 1 }, {
      forceNetworkError: true
    }).as('failedProfile')
    cy.intercept('GET', '/api/profile', {
      statusCode: 200, body: { name: 'Asha' }
    }).as('recoveredProfile')

    cy.visit('/profile')
    cy.wait('@failedProfile').should('have.property', 'error')
    cy.contains('Try again').click()
    cy.wait('@recoveredProfile').its('response.statusCode').should('eq', 200)
    cy.contains('Asha').should('be.visible')
  })
})

5. Dynamic Route Handlers

Q: What is the req object in a route handler?

It represents the outgoing intercepted request and exposes the request URL, method, headers, body, and routing controls. You can mutate supported fields before the request continues, subscribe to lifecycle events, call req.reply() to provide a response, or call req.continue() to reach the destination. Because the callback runs when traffic matches, it is suitable for conditional behavior based on the actual payload.

Q: What is the difference between req.reply() and req.continue()?

req.reply() ends request-phase routing by supplying or configuring the response. req.continue() sends the request onward and can accept a callback that inspects or modifies the real response. Call at most one terminal action for a matched request; invoking both expresses contradictory routing intent and does not model a coherent scenario.

Q: Can you modify outgoing request headers or bodies?

Yes. Assign supported request properties in the handler before continuing, such as adding an authorization header or changing a JSON body field. This can isolate a front-end scenario, but it can also conceal an application defect, so assert the precondition or reserve mutation for test-only integration needs. Changes made by Cypress may not appear in the browser DevTools request display because interception occurs after the browser has initiated the request.

Q: How do you inspect or change a real response?

Pass a callback to req.continue(). The callback receives res, where you can assert or adjust properties such as status, headers, body, delay, or throttle behavior before the application receives the response. Use this sparingly: modifying a live response creates a hybrid test whose ownership should be obvious from its name.

cy.intercept('GET', '/api/account', (req) => {
  req.headers['x-test-run'] = 'network-interview'
  req.continue((res) => {
    expect(res.statusCode).to.eq(200)
    res.headers['cache-control'] = 'no-store'
  })
}).as('account')

6. Timing, Ordering, and Multiple Matchers

Q: Why must an interceptor usually be registered before cy.visit()?

Applications often issue bootstrap requests during page load. If cy.visit() runs first, the request may complete before the following cy.intercept() registers, leaving cy.wait() with nothing to observe. Register routes before the action that triggers traffic, including visits, clicks, form submissions, timers, or viewport-driven lazy loading.

Q: What happens when multiple interceptors match one request?

Cypress can run more than one matching route according to its routing algorithm. Normal routes are evaluated in reverse order of definition, while { middleware: true } routes run first in definition order. A handler that replies ends request-phase propagation; a handler that does not terminate routing allows later applicable handlers to participate.

Q: When is middleware: true appropriate?

Use middleware when a broad handler must consistently run before ordinary routes, perhaps to remove cache headers or attach test metadata. It changes ordering semantics, so it should be rare and clearly named. Do not use it as a repair for vague matchers; first make each route's scope precise.

Q: What does the times matcher do?

times limits how many matches a route handles. It is ideal for a first-call failure followed by a normal response, because the exceptional route automatically expires after the declared count. Pair it with an assertion on the recovery behavior so the test proves the application retried rather than merely defining two routes.

7. GraphQL and Shared Endpoints

Q: Why is GraphQL harder to match by URL alone?

Many GraphQL operations share one POST endpoint, so method plus pathname identifies transport but not intent. Inspect req.body.operationName, or a stable query marker when operation names are unavailable, then assign a request alias or conditional reply. Operation names are preferable because string matching an entire query is sensitive to formatting and generated-document changes.

Q: How do you give different GraphQL operations different aliases?

Register one handler for the GraphQL endpoint and set req.alias dynamically after reading operationName. A test can then wait for @GetProjects or @CreateProject even though both calls use /graphql. Validate the body before accessing it because persisted queries or alternative clients may encode requests differently.

Q: How do you stub only one GraphQL operation?

Conditionally call req.reply() only when the target operation matches. Let other operations continue without replying, which preserves their normal routing. Include the GraphQL envelope, typically a top-level data or errors property, because returning a REST-shaped body can create a false UI failure unrelated to the scenario.

Q: How should GraphQL errors be tested?

Distinguish transport errors from GraphQL execution errors. A GraphQL resolver failure can arrive with HTTP 200 and an errors array, while authentication infrastructure might return 401 or 403. Stub the form your client actually handles and assert whether it displays partial data, an operation-level message, or a global error boundary.

cy.intercept('POST', '/graphql', (req) => {
  const operationName = req.body && req.body.operationName
  if (operationName === 'GetProjects') {
    req.alias = 'GetProjects'
    req.reply({
      statusCode: 200,
      body: { data: { projects: [{ id: 'p1', name: 'QA Portal' }] } }
    })
  }
})
cy.visit('/projects')
cy.wait('@GetProjects').its('request.body.operationName').should('eq', 'GetProjects')
cy.contains('QA Portal').should('be.visible')

For broader API preparation, compare these patterns with API testing interview questions and API error handling and negative testing.

8. Caching, Service Workers, and Browser Boundaries

Q: Why might an expected request never reach cy.intercept()?

The browser may serve a cached resource without sending a network request, the application may reuse in-memory state, or a service worker may satisfy it. Registration could also be late, the matcher could be wrong, or the traffic could originate outside the browser context Cypress instruments. Diagnose in that order by confirming the application action, inspecting the Cypress command log, and checking cache and service-worker behavior.

Q: How can caching affect interception tests?

If the browser cache fulfills the resource, no request crosses the network layer and no route can match it. For test environments, configure the server to send suitable cache directives or use a response-phase handler to remove caching headers from real responses. Avoid globally disabling realistic caching unless the test objective specifically requires fresh traffic, because cache behavior can itself be a product risk.

Q: Does cy.intercept() intercept cy.request() calls?

No. cy.request() is issued by Cypress outside the application's browser request pipeline, so a browser interception route does not capture it. Assert the result returned by cy.request() directly, and use cy.intercept() for traffic produced by the page. This distinction is a frequent interview check for understanding Cypress architecture rather than mere syntax.

Q: Can Cypress modify third-party requests?

It can match browser requests by hostname and URL, subject to the application's behavior and Cypress browser constraints. Stubbing third-party analytics or unstable dependencies may improve determinism, but broad interception can hide integration breakage. Match the exact host and path, avoid capturing secrets in logs, and retain separate coverage for business-critical third-party contracts.

9. Latency, Throttling, and Race Conditions

Q: How do you test a loading spinner with interception?

Delay the stubbed response long enough for the loading state to be observable, then assert the spinner appears before the data and disappears afterward. The delay is scenario control, not synchronization; still wait on the route alias and assert final UI state. Keep the delay modest so the test proves state transitions without adding excessive suite time.

Q: What is the difference between delay and throttleKbps?

delay holds the response for a fixed number of milliseconds before delivery. throttleKbps constrains transfer throughput, making payload size relevant to completion time. Choose delay for deterministic loading-state tests and throttling when progressive transfer or slow-connection behavior is the actual risk.

Q: Can network interception expose front-end race conditions?

Yes. Delay an earlier search response so a later query returns first, then verify stale data cannot overwrite the latest results. This tests cancellation, request identity, or reducer logic that fast local networks often conceal. Use distinct response markers for each query so the final assertion unambiguously identifies which result won.

Q: Why are arbitrary cy.wait(2000) calls inferior here?

A fixed delay knows nothing about the request lifecycle and can be both too short on CI and unnecessarily slow locally. An aliased route waits for the meaningful event and returns diagnostic data when assertions fail. Numeric waits remain defensible only when elapsed time itself is the behavior under test and there is no observable event to synchronize against.

10. Debugging Failed Interceptions

Q: How do you debug a cy.wait('@alias') timeout?

Confirm that the triggering action happened and that interception registration preceded it. Compare the real method, origin, pathname, and query with the matcher, then narrow or correct the pattern. Also check caching, service workers, conditional feature flags, and whether the request was sent by cy.request() rather than the page.

Q: Why can a URL look correct but still fail to match?

The actual URL may include a different origin, base path, encoded value, trailing slash, or query representation. A method mismatch is equally easy to overlook. Prefer a RouteMatcher with explicit pathname and relevant query keys, then read the command log route table instead of guessing from the visible page URL.

Q: How do you prove an interceptor is too broad?

Temporarily log or collect matched request methods and URLs inside the handler, then exercise one scenario. If unrelated resources appear, tighten the hostname, pathname, method, headers, or query. A strong permanent assertion waits for the intended alias and checks a defining request property, making future endpoint drift fail loudly.

Q: What should you inspect when the stub matches but the UI still fails?

Inspect the response schema, content type, status, and required headers against what the application client expects. Confirm field types, nesting, nullability, and GraphQL envelopes, then check the browser console for parsing or rendering errors. Finally assert that the UI action consumes the same endpoint; a successful alias can coexist with a separate failing request.

The guide to capturing Cypress network traffic helps when request details are unclear, while handling flaky Cypress tests covers broader synchronization problems.

11. Test Design and Coverage Trade-offs

Q: What are the risks of overusing stubs?

A stub can drift from the provider contract while every UI test stays green. It also bypasses authentication, serialization, infrastructure, and data behavior that may be responsible for real defects. Mitigate this with a small set of live end-to-end paths, contract tests, schema validation, and explicit ownership for updating representative fixtures.

Q: Which scenarios benefit most from network stubbing?

Rare failures, destructive operations, boundary payloads, empty states, slow responses, and hard-to-create permission combinations benefit strongly. Stubbing also isolates front-end rendering when a backend is unavailable during parallel development. It adds less value when the purpose is to verify deployment wiring, authorization integration, or the actual data contract.

Q: Should request assertions replace UI assertions?

No. A correct request proves the browser attempted the right operation, but it does not prove the user saw confirmation, validation, or recovered state. Combine a focused network assertion with a user-visible outcome. This pairing localizes failures while preserving the business purpose of an end-to-end test.

Q: How do you keep fixtures maintainable?

Organize them by domain and scenario, use realistic minimal payloads, and avoid one enormous object shared by unrelated tests. Validate important fixtures against an API schema or contract in CI where possible. Name exceptional fixtures by behavior, such as projects-empty.json or checkout-card-declined.json, so reviewers understand why each variant exists.

12. Senior Cypress Network Interception Interview Questions

Q: How would you design interception helpers without hiding Cypress behavior?

Create small domain helpers that register named routes and return no invented chainable abstraction. Keep matchers and aliases visible, accept only scenario data that varies, and let tests call standard cy.wait() themselves. Avoid a universal intercept factory with dozens of options because it obscures route order, terminal handlers, and the exact response under review.

Q: How would you test an application retry policy?

Use a times: 1 route to fail the first request, then a success route for the next call. Capture timestamps or counts in handlers if backoff itself matters, but tolerate a bounded range rather than asserting an exact millisecond. Verify the user does not receive duplicate records or stale errors after recovery, since retry correctness includes idempotency and state cleanup.

Q: How would you prevent intercepted auth tokens from leaking?

Do not print complete headers or bodies that may contain credentials, personal data, or payment information. Assert token presence or a safe prefix without embedding a production secret in code, and use synthetic test accounts. Sanitize diagnostic tasks and CI artifacts, because interception makes sensitive traffic easy to expose accidentally.

Q: How do you decide between interception, cy.request(), and contract tests?

Use interception when browser behavior depends on a request or response. Use cy.request() for direct setup, cleanup, and API checks that do not need the UI. Use contract tests to verify consumer-provider compatibility across a broad schema and interaction set; the layers complement one another rather than compete. See API contract testing with Pact for the provider-consumer layer.

Q: What would you review in a pull request containing many interceptors?

Check registration timing, matcher precision, alias clarity, route ordering, realistic contracts, and assertions on user outcomes. Look for secrets, fixed delays, duplicated fixture payloads, and stubs that make the stated integration goal impossible. Ask which risks remain covered by real services and whether each exceptional route proves a distinct behavior.

How Interviewers Grade Your Answers

Interviewers usually score four dimensions. First, syntax accuracy: use real APIs such as cy.intercept(), req.reply(), req.continue(), dynamic req.alias, times, delay, and forceNetworkError in their proper roles. Second, lifecycle understanding: explain that registration precedes the trigger, browser traffic is distinct from cy.request(), and cy.wait() yields an interception.

Third, test judgment matters more at senior levels. State why you would spy or stub, what confidence the chosen approach sacrifices, and which complementary layer covers that gap. Fourth, debugging quality separates production experience from memorization: a useful answer checks the trigger, route table, method, URL components, cache, service worker, response schema, and multiple matching handlers systematically.

When asked to write code, narrate the causal chain: register the matcher, alias it, trigger the application request, wait for the alias, assert the network contract, and assert the user-visible result. Practice this pattern in the QA interview practice area or upload your resume in the QAJobFit dashboard to align preparation with the roles you target.

Common Mistakes

  • Registering the interceptor after cy.visit() or after the click that sends the request.
  • Matching ** or a shared GraphQL URL without distinguishing the business operation.
  • Calling every HTTP 500 response a network failure instead of using forceNetworkError for connection failure.
  • Replacing event-based synchronization with arbitrary numeric waits.
  • Asserting only the stub status while ignoring whether the UI rendered, recovered, or submitted correctly.
  • Returning an unrealistic payload that omits required nesting, headers, or GraphQL envelopes.
  • Assuming browser DevTools shows mutations made after Cypress captured the outgoing request.
  • Expecting cy.intercept() to observe cy.request() traffic.
  • Creating overlapping handlers without understanding reverse definition order and middleware priority.
  • Stubbing every endpoint until the suite no longer tests backend integration.
  • Logging authorization headers or personal data into CI output.
  • Sharing giant fixtures whose unrelated edits break dozens of tests.

Conclusion

The best answers to Cypress network interception interview questions connect API syntax to test intent. Explain the route lifecycle, match narrowly, synchronize with aliases, prove both the exchange and the UI outcome, and state what a stub cannot validate.

Rehearse the runnable examples, then change each one to cover a timeout, a GraphQL error, a retry, and a stale-response race. That exercise demonstrates the practical judgment interviewers expect from a tester who will maintain real Cypress suites.

Interview Questions and Answers

What does cy.intercept do in Cypress?

It registers a route that can observe or control HTTP traffic produced by the application under test. Without a response handler it spies on the real exchange. With a static response or callback it can stub, modify, delay, or fail the exchange.

What does cy.wait on an intercept alias return?

It yields an interception object containing the outgoing request and, for a completed HTTP exchange, the response. I inspect method, URL, body, status, headers, and response body there. A forceful network failure exposes an error rather than a normal response.

Why register cy.intercept before cy.visit?

Many applications issue bootstrap requests during page load. Registering afterward creates a race in which the request can finish before Cypress starts observing it. I define the route first, then perform the action that triggers traffic.

How do req.reply and req.continue differ?

`req.reply()` supplies or configures a response and ends request-phase routing. `req.continue()` sends the request to its destination and can inspect or modify the real response in a callback. I use only one terminal action for a matched request.

How do you intercept individual GraphQL operations?

I match the shared GraphQL endpoint and inspect `req.body.operationName`. I can assign `req.alias` dynamically or call `req.reply()` only for the chosen operation. The stub must use a valid GraphQL `data` or `errors` envelope.

How do you simulate one failed request followed by success?

I define a failure route with `times: 1`, then a normal success route for later traffic. The first handler expires after one match. I verify the retry occurred and that the final UI has neither duplicate state nor a stale error.

Why might cy.intercept not see a browser request?

The interceptor may be late or its method, path, origin, or query may not match. The browser could also serve cached data, an application store could reuse data, or a service worker could respond. Traffic generated by `cy.request()` is outside this interception pipeline.

How do you test loading behavior with cy.intercept?

I add a modest `delay` to a controlled response, assert the loading indicator appears, wait on the aliased route, and assert the final content replaces it. The delay creates the scenario, while the alias provides synchronization.

What are the risks of over-mocking network calls?

Mocks can drift from real schemas and bypass authentication, serialization, infrastructure, and data defects. A fully stubbed suite may stay green while production integration is broken. I balance focused stubs with live end-to-end paths and contract tests.

How are multiple matching interceptors ordered?

Routes with `middleware: true` run first in definition order. Ordinary matching routes are considered in reverse definition order. A replying handler ends request-phase propagation, so I keep overlapping matchers rare and document intentional layering.

Frequently Asked Questions

What is Cypress network interception?

Cypress network interception observes or controls HTTP requests made by the application in the browser. The `cy.intercept()` command can spy on real exchanges or provide controlled responses for deterministic UI scenarios.

Does cy.intercept work with fetch requests?

Yes. `cy.intercept()` handles browser `fetch` and XMLHttpRequest traffic without requiring `cy.server()`. Register it before the application sends the request.

Why does cy.wait say no request ever occurred?

The route may have been registered too late, matched the wrong method or URL, or the browser may have used cached or in-memory data. Confirm the trigger first, then compare the actual request with the matcher and inspect service-worker behavior.

Can cy.intercept intercept cy.request?

No. `cy.request()` runs outside the application's browser network pipeline. Assert its returned response directly and reserve `cy.intercept()` for requests initiated by the page.

How do you mock a 500 response in Cypress?

Pass a static response such as `{ statusCode: 500, body: { message: 'Server error' } }` to `cy.intercept()`. Trigger the request and assert the application's visible error and recovery behavior.

How do you intercept a GraphQL request in Cypress?

Match the GraphQL POST endpoint, inspect `req.body.operationName`, and assign a dynamic alias or conditional reply. Return a valid GraphQL envelope with `data` or `errors`.

Should every Cypress test stub network calls?

No. Stubs are excellent for deterministic edge cases, but they can drift from the real service. Retain live integration paths and contract coverage for authentication, deployment wiring, and schema compatibility.

Related Guides