0
0
Cypresstesting~15 mins

cy.intercept() for request interception in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - cy.intercept() for request interception
What is it?
cy.intercept() is a command in Cypress that lets you watch, modify, or block network requests made by your web application during testing. It helps you control how your app communicates with servers by intercepting HTTP requests and responses. This allows you to simulate different server behaviors without needing a real backend. It is useful for testing how your app handles various server responses and network conditions.
Why it matters
Without cy.intercept(), tests depend on real servers and network conditions, which can be slow, unreliable, or hard to control. This makes tests flaky and slow. cy.intercept() solves this by letting you simulate server responses instantly and consistently. This means faster, more reliable tests that can cover edge cases like errors or slow responses easily. It helps developers catch bugs early and deliver better software.
Where it fits
Before learning cy.intercept(), you should understand basic Cypress commands and how web apps make HTTP requests. After mastering cy.intercept(), you can learn advanced testing topics like stubbing, mocking APIs, and testing error handling. It fits into the journey of writing robust end-to-end tests that do not rely on real backend services.
Mental Model
Core Idea
cy.intercept() acts like a traffic controller that watches and changes network requests your app makes during tests.
Think of it like...
Imagine a mailroom clerk who intercepts letters going out or coming in, reading or changing them before they reach their destination. cy.intercept() is that clerk for your app's network messages.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Your App      │──────▶│ cy.intercept()│──────▶│ Server or Stub│
│ (makes HTTP)  │       │ (intercepts)  │       │ (responds)    │
└───────────────┘       └───────────────┘       └───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding HTTP Requests in Tests
🤔
Concept: Learn what HTTP requests are and why tests need to observe them.
Web apps communicate with servers using HTTP requests like GET or POST. During tests, these requests fetch or send data. Observing these requests helps verify if the app behaves correctly. Without interception, tests wait for real servers, which can be slow or unpredictable.
Result
You understand that network requests are key to app behavior and testing them is important.
Knowing that your app talks to servers via HTTP requests sets the stage for controlling these requests in tests.
2
FoundationBasic Usage of cy.intercept()
🤔
Concept: Learn how to use cy.intercept() to watch a network request.
Use cy.intercept('GET', '/api/data') to listen for GET requests to '/api/data'. When the app makes this request, Cypress notices it. You can then add assertions to check if the request happened.
Result
Tests can detect when specific requests are made.
Simply watching requests helps confirm your app triggers expected network calls.
3
IntermediateStubbing Responses with cy.intercept()
🤔Before reading on: do you think cy.intercept() can change the server's response or only watch requests? Commit to your answer.
Concept: Learn how to replace real server responses with fake data.
You can pass a response object to cy.intercept() to stub the server reply. For example, cy.intercept('GET', '/api/data', { fixture: 'data.json' }) returns predefined data instantly. This avoids real network calls and lets you test app behavior with controlled data.
Result
Tests run faster and can simulate different server responses reliably.
Stubbing responses lets you test how your app handles various data or errors without depending on real servers.
4
IntermediateModifying Requests and Responses Dynamically
🤔Before reading on: can cy.intercept() change requests before they reach the server? Commit to your answer.
Concept: Learn to modify requests or responses on the fly using callback functions.
cy.intercept() accepts a function to inspect and change requests or responses. For example, you can add headers, delay responses, or simulate errors dynamically. This helps test complex scenarios like slow networks or authentication failures.
Result
Tests can simulate real-world network conditions and edge cases.
Dynamic modification of network traffic makes tests more realistic and robust.
5
AdvancedUsing Aliases and Waiting for Requests
🤔Before reading on: do you think you can pause test steps until a network request finishes? Commit to your answer.
Concept: Learn to assign aliases to intercepted requests and wait for them in tests.
Use cy.intercept().as('getData') to name a request. Then use cy.wait('@getData') to pause test execution until that request completes. This ensures your test checks app state only after data loads.
Result
Tests become more reliable by synchronizing with network activity.
Waiting for requests prevents flaky tests caused by timing issues.
6
ExpertHandling Multiple Intercepts and Overlapping Requests
🤔Before reading on: what happens if two intercepts match the same request? Commit to your answer.
Concept: Learn how Cypress chooses which intercept to apply when multiple match and how to manage complex scenarios.
Cypress applies the first matching intercept in the order they were declared. You can use routeMatcher options like method, URL, or headers to narrow matches. For overlapping intercepts, carefully order them or use conditional logic in callbacks to avoid conflicts.
Result
You can write complex tests with multiple intercepts without unexpected behavior.
Understanding intercept priority and matching rules prevents subtle bugs in tests with many network controls.
Under the Hood
cy.intercept() hooks into the browser's network layer using Cypress's internal proxy. When the app sends an HTTP request, Cypress intercepts it before it reaches the server. It can then modify, block, or respond to the request directly. This interception happens asynchronously and integrates with Cypress's command queue to synchronize test steps.
Why designed this way?
Cypress was designed to control the browser fully for reliable testing. Intercepting network requests at the proxy level allows tests to simulate any server behavior without changing app code or backend. This design avoids flaky tests caused by real network variability and enables powerful mocking capabilities.
┌───────────────┐
│ Browser App   │
│ (makes HTTP)  │
└──────┬────────┘
       │ HTTP Request
       ▼
┌───────────────┐
│ Cypress Proxy │◀─────────────┐
│ (intercepts)  │              │
└──────┬────────┘              │
       │ Modify/Stub/Block      │
       ▼                       │
┌───────────────┐              │
│ Real Server   │──────────────┘
│ or Stubbed    │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does cy.intercept() automatically block all network requests it matches? Commit to yes or no.
Common Belief:cy.intercept() blocks all matched requests by default.
Tap to reveal reality
Reality:cy.intercept() only blocks requests if you provide a stubbed response or explicitly modify it. Otherwise, it lets the request continue to the server.
Why it matters:Assuming all requests are blocked can cause confusion when tests unexpectedly hit real servers, leading to flaky tests.
Quick: Can cy.intercept() intercept requests made before the test starts? Commit to yes or no.
Common Belief:cy.intercept() can catch any request the app makes, even before the test runs.
Tap to reveal reality
Reality:cy.intercept() only intercepts requests made after it is declared in the test code.
Why it matters:If you set intercepts too late, you might miss important requests, causing tests to behave unpredictably.
Quick: Does cy.intercept() replace the need for backend testing? Commit to yes or no.
Common Belief:Using cy.intercept() means you don't need to test the backend separately.
Tap to reveal reality
Reality:cy.intercept() only simulates backend responses in tests; it does not verify backend correctness or performance.
Why it matters:Relying solely on intercepts can miss backend bugs, so backend testing remains essential.
Quick: If two intercepts match the same request, will both run? Commit to yes or no.
Common Belief:All matching intercepts run for the same request.
Tap to reveal reality
Reality:Only the first matching intercept declared runs; others are ignored for that request.
Why it matters:Misunderstanding this can cause unexpected test behavior when multiple intercepts overlap.
Expert Zone
1
Intercepts are stateful within a test run; resetting or re-declaring them affects subsequent requests.
2
Using routeMatcher options precisely avoids unintended matches and improves test clarity.
3
Delays or throttling in intercept responses simulate network latency realistically but can slow tests if overused.
When NOT to use
Avoid using cy.intercept() for testing backend logic or database interactions; use dedicated backend tests instead. Also, do not rely on intercepts for performance testing since they bypass real network conditions unless explicitly simulated.
Production Patterns
In real-world tests, cy.intercept() is used to stub third-party APIs, simulate error responses, and speed up tests by avoiding slow backend calls. Teams often combine intercepts with fixtures for consistent test data and use aliases to synchronize complex UI flows.
Connections
Mocking in Unit Testing
cy.intercept() builds on the idea of mocking external dependencies to isolate tests.
Understanding mocking helps grasp why intercepting network calls improves test reliability by controlling external factors.
Proxy Servers in Networking
cy.intercept() acts like a proxy server that can inspect and modify traffic.
Knowing how proxies work clarifies how Cypress intercepts requests without changing app code.
Quality Control in Manufacturing
Intercepting requests is like quality inspectors checking products before shipping.
This connection shows how interception ensures only correct data flows through, similar to catching defects early.
Common Pitfalls
#1Intercept declared after the request is sent.
Wrong approach:cy.visit('/'); cy.intercept('GET', '/api/data');
Correct approach:cy.intercept('GET', '/api/data'); cy.visit('/');
Root cause:Intercepts only catch requests made after they are declared; declaring too late misses requests.
#2Assuming cy.intercept() blocks requests without stubbing.
Wrong approach:cy.intercept('GET', '/api/data'); // expects request blocked
Correct approach:cy.intercept('GET', '/api/data', { fixture: 'data.json' }); // stubs response
Root cause:Without a stub or modification, requests pass through; misunderstanding this causes flaky tests.
#3Using broad intercepts that match unintended requests.
Wrong approach:cy.intercept('GET', '/api/*');
Correct approach:cy.intercept({ method: 'GET', url: '/api/data' });
Root cause:Overly broad matching causes conflicts and unexpected test behavior.
Key Takeaways
cy.intercept() lets you watch and control network requests your app makes during tests.
It improves test speed and reliability by simulating server responses without real network calls.
You must declare intercepts before the requests happen to catch them.
Using aliases and waiting for requests helps synchronize tests with app behavior.
Understanding intercept priority and matching rules prevents subtle test bugs.