Cypress provides a complete package for End to End automation, it can help you with UI automation, API automation and web application automation. Cypress is a Unique tool that makes all the tasks associated with test automation very easy and doable, In addition to that it can provide you a functionality called Intercept which helps in mocking or stubbing the request and its associated response. Using which user can active test automation and its running ability can be assured even if api services are down.
What is Intercept ?
cy.intercept() is a relatively new concept in Cypress that allows for monitoring and controlling interactions between an application and web services or third-party APIs. This feature is particularly useful during test automation because it enables control over the application’s requests and responses, even when the external APIs or services are unavailable.cy.intercept() is a relatively new concept in Cypress that allows for monitoring and controlling interaction of the application with the web services or third party API.
Why to use Cypress Intercept
There are various reasons why we are using Cypress Intercept, the most important reason is the ease of its usage for performing Mocking and stubbing. We can easily take control of requests and responses that are performing communication between applications and API or services and make required changes in that. We can even take a record for all these transactions and use these responses in the absence of an API backend.
We can use Cy.intercept for manipulating network requests that were made by the application during testing, we can intercept specific HTTPS requests, determine its properties and then decide how we are going to respond to the same.
With the help of Cypress intercept, we can perform performance testing, security testing and reduce the risk of test flakiness, reduce the number of false failures and perform testing of edge cases .
What is Mocking?
Mocking or Stubbing is the process of providing predefined responses to specific requests. We use this technique when we want to remove our dependency from all the third party services, there are cases when these third party API services are not stable enough and we are not getting desired support. So for resolving this issue we create responses for the required request and make sure whenever automation hits the backend with a request which involves third party dependency, it will get the already defined response.
How can we use Cypress Intercepts for Security and performance testing?
Using Cypress Intercepts we can explore different dimensions and scope of testing.
To perform security testing using Cypress, you can simulate user inputs to test for cross-site scripting (XSS) vulnerabilities and ensure that inputs are sanitized. Below is an example code snippet for testing XSS. To perform security testing using Cypress, you can simulate user inputs to test for cross-site script.
// Example: Testing for XSS
cy.visit('https://gift.com');
cy.get('#inputField').type('<script>alert("XSS");</script>');
cy.get('#submitButton').click();
cy.get('#outputDiv').should('not.contain', '<script>');
Another way of performing security testing is request intercept, by which while intercepting requests and responses we can perform checks for security headers, response code and other information which can impact security. Below is the example code for doing this.
// Example: Intercepting and checking response headers
cy.intercept('GET', '/api/sensitive-data').as('sensitiveData');
cy.visit('https://gift.com');
cy.wait('@sensitiveData').its('response.headers').should('include', 'X-Content-Type-Options');
For performing Performance testing intercept is a very useful tool, we can use the below techniques for doing that.
By using Network Throttling, we can simulate various network conditions such as slow connections, delayed responses and check how an application is behaving under these conditions and design multiple scenarios around it.
Below is the example code for that.
// Example: Simulating slow network
cy.intercept('GET', '/api/data').as('getData');
cy.visit('https://example.com');
cy.wait('@getData', { timeout: 10000 }); // Wait for the request to complete
cy.intercept('GET', '/api/data').throttle(5000); // Simulate a slow network
cy.reload();
cy.wait('@getData', { timeout: 15000 }); // Wait for the request to complete with throttling
Another way of doing this is Performance metrics, we use additional plugins in cypress like Cypress pref, Lighthouse for performing this, by using these tools we can analyze and collect performance metrics such as page load times, resource sizes and more.
Below is the example code for doing this.
// Example: Using cypress-perf to collect performance metrics
const { analyze } = require('cypress-perf');
describe('Performance Testing', () => {
it('should load the page quickly', () => {
cy.visit('https://example.com');
analyze();
});
});
How to use Cypress Intercepts?
We can use cypress intercepts in multiple ways, below are some of the most used ways by which we can use Cy.Intercept().
Using cy.intercept() for Intercepting Network Requests:
We can use “cy.intercept()” for intercepting network requests and responding to them back as per the requirements from the test.
In the below snippet cypress is intercepting a GET request which is coming to ‘/api/inters’ and responds back with the data stored in the fixture file named as ‘inter.json’
cy.intercept('GET', '/api/inters’, { fixture: 'inter.json' }).as('getInter');
Modifying responses:
We can perform modifications in the intercepted request and responses.
In the below snippet cypress is intercepting a request with PUT command for updating a user and it is responding back with a modified response having updated user data.
cy.intercept('PUT', '/api/users/1', (req) => {
req.reply({ statusCode: 200, body: { id: 1, name: 'Updated User' } });
}).as('updateUser');
Stubbing/Mocking Requests:
Using intercept we can perform stubbing, with the help of stub network requests we can prevent requests to reach the network. In place of that it can be redirected to a stubbed server and from there it can get the response which is mocked by the user.
cy.intercept('POST', '/api/login', {
statusCode: 200,
body: { token: 'mocked-token' },
}).as('loginRequest');
Aliasing and waiting:
After intercepting a request, you can use the .as() method to alias the intercepted request and use cy.wait() to pause test execution until the request is complete.
cy.intercept('GET', '/api/data').as('getData');
// Perform actions that trigger the GET request
cy.wait('@getData');
In the next section you will see how cy.intercept() works and what are the various ways for Intercepting Network Requests in Cypress.
How does the cy.intercept() method work?
cy.intercept() in Cypress is such a useful feature to enable intercepting the modifying of HTTP requests and responses while testing. It helps be in control of how your application behaves with respect to certain network interactions, emulates certain network conditions, or fake responses to calls without actually having to get the backend involved.

Steps in the Diagram:
- Client Sends Request: The browser which is the client starts the request message to the server.
- Server Receives Request: The request returns to the server and the server proceeds to respond.
- Cypress Intercepts Request: Cypress test code ‘gets in between’ the request before it gets to the server and can alter the request.
- Modify or Stub Response: The test code can change the request (for example change headers or parameters) or replace the response in whole. This means that you can send a mocked response and this will be realized by the client that it has received it from the server.
- Client Receives Stubbed Response: The client analyzes the stubbed response as if it was issued from the actual server. This makes it possible for you to see how the application functions without having to call the actual network.
Approaches for Intercepting Network Requests in Cypress
In Cypress, there are several ways to intercept network requests using the cy.intercept() method, allowing for flexible control over network interactions.
Here are some of the ways by which you can handle network requests using Cypress Intercept:
Matching the URL
You can intercept a request based on a specific URL. This is the most basic and common way to use cy.intercept().
cy.intercept('/api/users').as('getUsers');
// Wait for the intercepted request
cy.wait('@getUsers');
In this example, Cypress intercepts any request made to /api/users, regardless of the HTTP method
Example
Let’s take the example of the site https://reqres.in/ .
In the below example, you can see we are intercepting a network request made to https://reqres.in/api/users/ without specifying an HTTP method, meaning it intercepts requests to the given URL regardless of whether they are GET, POST, etc.
it("Matching URL without any Method", () => {
cy.visit("https://reqres.in/");
cy.intercept("https://reqres.in/api/users/").as("posts");
cy.get("[data-id=users]").click()
cy.wait("@posts").its("response.body.data").should("have.length", 6);
})
Output
Run the above code which executed successfully

HTTPS Method Matching
You can also intercept requests based on the HTTP method (e.g., GET, POST, PUT, DELETE). This adds another level of precision to your interception.
cy.intercept('GET', '/api/users').as('getUsers');
// Intercept only GET requests to the specified URL
cy.wait('@getUsers');
This example ensures that only GET requests to /api/users are intercepted, ignoring any other methods (e.g., POST or PUT).
Example
The second way of intercepting the request is by Matching the methods. By default, if you don’t specify a method argument, then all the HTTP methods (GET / POST / PUT / PATCH / DELETE / etc.) will match. When passing into the function cy.intercept() it allows for the interception of a particular method call made in a network request.
In the below example you can see we are intercepting a GET request to the /api/users?page=2 endpoint when visiting https://reqres.in/ and waiting for the response to ensure it contains 6 users in the response body.
it("Matching URL by GET method", () => {
cy.visit("https://reqres.in/");
cy.intercept("GET", "/api/users?page=2").as("posts");
cy.get("[data-id=users]").click()
cy.wait("@posts").its("response.body.data").should("have.length", 6);
})
Output
Run the above code which executed successfully

Matching with RouteMatcher
RouteMatcher allows for more advanced matching by specifying properties such as the URL, method, headers, and even request body content.
cy.intercept({
method: 'POST', // Match method
url: '/api/users', // Match URL
headers: { 'Content-Type': 'application/json' } // Match headers
}).as('createUser');
This method lets you match requests with multiple criteria, offering fine control over how and when the intercept happens.
Example
In the below example, a RouteMatcher is utilized to intercept any GET request directed at the https:The request is send to the /reqres.in/api/users/** url. With the use of the **, it is given the possibility to capture any path following /api/users/.
We then use the req.reply() function, to return a custom response for these intercepted requests. Last, we load the application and verify that the response has 2 items.
it("Intercept by RouteMatcher", () => {
cy.visit("https://reqres.in/");
cy.intercept(
{
method: "GET",
url: "https://reqres.in/api/users/**",
},
(req) => {
// Provide a custom stubbed response
req.reply({
statusCode: 200,
body: {
data: [
{
id: 1,
email: "george.bluth@reqres.in",
first_name: "George",
last_name: "Bluth",
avatar: "https://reqres.in/img/faces/1-image.jpg",
},
{
id: 6,
email: "tracey.ramos@reqres.in",
first_name: "Tracey",
last_name: "Ramos",
avatar: "https://reqres.in/img/faces/6-image.jpg",
},
],
},
});
}
).as("getUsers");
// Wait for the intercepted request and assert the stubbed response contains 2 users
cy.wait("@getUsers").its("response.body.data").should("have.length", 2);
});
Output
Run the above code which executed successfully

Pattern Matching
You can use string patterns (like wildcards) or regular expressions to match URLs dynamically. This is useful when the exact URL changes but follows a predictable pattern.
cy.intercept('/api/*').as('anyApiRequest');
// Intercept any API request with /api in the URL
cy.wait('@anyApiRequest');
cy.intercept(/\/api\/users\/\d+/).as('getUserById');
// Intercept requests like /api/users/123
cy.wait('@getUserById');
Here, the wildcard * matches any path after /api/, and the regular expression matches URLs like /api/users/1.
Example
In the code below cy.intercept set-up an intercept for HTTP requests and listens for DELETE, GET, or POST requests whose URL matches the pattern **/users/**.
Alias @postdata to the intercepted request, making it easier to reference later in the test.
Finally It checks that the data array in the response body has a length of 2, confirming that two user objects were included in the mocked response.
it('Intercept by Pattern Matching ', () => {
cy.visit('https://reqres.in/')
cy.intercept({
method: '+(DELETE|GET|POST)',
url: '**/users/**'
}, (req) => {
req.reply({
statusCode: 200,
body: {
data: [{
id: 6,
"email": "tracey.ramos@reqres.in",
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://reqres.in/img/faces/6-image.jpg"},{
id: 3,
"email": "emma.wong@reqres.in",
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https://reqres.in/img/faces/3-image.jpg"}, {
id: 8,
email: 'janet.weaver@reqres.in',
first_name: 'Janet',
last_name: 'Weaver',
avatar: 'https://reqres.in/img/faces/2-image.jpg'}]}
})
}).as('postdata')
cy.wait('@postdata').its('response.body.data').should('have.length', 3)
})
Output
Run the above code which executed successfully

Conclusion:
In conclusion, Cypress intercept offers a robust solution for stubbing, mocking, and modifying network requests in test automation. It enhances efficiency by providing control over HTTP interactions and ensures reliable tests even without a live API, making it ideal for handling edge cases and reducing test flakiness.