SlideShare a Scribd company logo
2
Most read
How to use Cypress Intercept to Stub API Responses.pdf
How to use Cypress Intercept to Stub
API Responses
Cypress is a Unique tool it 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 ?
Intercept is a fairly new concept in the world of service virtualization, the
“cy.intercept()” is a very powerful concept, using this we can monitor all the
interaction of the application with the webservices or third party API. During
test automation and execution it becomes extra useful as we can control
various aspects of applications and its interaction with external API and
services.
Why 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 which are
performing communication between application 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 which were
made by 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 are 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.
For performing Security testing using Cypress we can do Cross -site
scripting testing by which we can simulate user inputs and check if they are
getting sanitised for preventing XSS vulnerabilities below is the code
snippet which is showing an example for implementing.
// 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 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 analyse and collect the 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 most used
ways by which we can use Cy.Intercept().
1. 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 fixture file named
as ‘inter.json’
cy.intercept('GET', '/api/inters, { fixture: 'inter.json' }).as('getInter');
2. Modifying responses:
We can perform modification 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.
Copy
cy.intercept('PUT', '/api/users/1', (req) => {
req.reply({ statusCode: 200, body: { id: 1, name: 'Updated User' } });
}).as('updateUser');
3. 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');
4. Aliasing and waiting:
After performing an intercept we can use the concept of aliasing using
‘.as()’ for the intercepted request and put a wait contention until it gets
completed.
cy.intercept('GET', '/api/data').as('getData');
// Perform actions that trigger the GET request
cy.wait('@getData');
Prerequisite for Cypress Intercepts?
For performing cypress Intercept operation few basic things are required
such as cypress installed and working, understanding of network request
and responses and commands like (HTTPS,PUT,POST,GET,DELETE).
Understanding of java script is also required for performing scripting .
Cypress Intercepts implementation
Here we are intercepting functionality and setting a response which will be
coming from the fixture file.
In the below example we are trying to describe how to perform cypress
intercept cy.intercept(). Firstly we need a request whether it is
GET/PUT/POST and we need to create a fixture file where we will be
storing the response which we want to send when the request comes in.
In the later part of the code we are using aliasing “.as(‘getPosts’)” the
request that it can be used further. After that we will be visiting the web
application and performing an action which later creates a GET request
and then we wait for it to get intercepted and then we send the response
which we have stored inside the fixture.
After that we verify the response assertion, whether the response contains
expected response code or elements in the body.
// my_test.spec.js
describe('Intercepting Network Requests', () => {
it('should intercept a GET request', () => {
// Intercept a GET request to a specific URL
cy.intercept('GET', '/api/posts', { fixture: 'posts.json' }).as('getPosts');
// Visit the page that triggers the GET request
cy.visit('/');
// Perform actions that trigger the GET request, e.g., click a button
// Wait for the intercepted request to complete
cy.wait('@getPosts').then((interception) => {
// Verify the response or perform assertions
expect(interception.response.statusCode).to.equal(200);
expect(interception.response.body).to.have.length(3); // Assuming
'posts.json' contains an array of 3 posts
});
});
});
Real time Implementation:
Here in this example we are setting the ERP details in fixtures so that when
user looks for particular ERP and in real time it is not available with the API
or we are not getting response from API, That time we can use the
response stored inside fixtures which contains details of ERP(name, ID and
other completion status). Once a request is submitted the response is
supplied back and the user can complete the test with this data.
cy.wait('@GetUserDetails').then((response) => {
cy.log(response);
});
.its('response.body.data.login')
.should('have.property', 'id')
.and('have.property', 'token');
Mocking example
cy.intercept('POST', '/graphql', (req) => {
if (req.body.operationName === 'GetErps') {
req.reply((res) => {
res.send({
data: {
erps: [
{
id: 'MyCustomERP1',
name: 'MyCustomERP1',
standard: true,
pipelineId: null,
extractType: ['REPORT'],
auditFirm: null,
__typename: 'Erp',
},
],
},
});
});
}
});
.as('GetErps');
});
Conclusion:
Cypress comes with a lot of libraries and functionalities, using which we
can perform End to End automation with great efficiency and speed.
Implementation of new concepts and techniques is fairly easy and
achievable. While performing Intercept it gives us a great amount of
flexibility to test the application in all possible perspectives, it reduces the
dependency of third party API’s and helps us to run our test cases
smoothly.
Source: This article was originally published at testgrid.io

More Related Content

PDF
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
PDF
Taming client-server communication
PDF
NodeJS and ExpressJS.pdf
PDF
ember-socket-guru - common api for websockets providers
PPTX
How to implement authorization in your backend with AWS IAM
PPT
Php & Web Security - PHPXperts 2009
PDF
Bt0083 server side programing
PDF
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
Mastering Cypress API Testing_ A Comprehensive Guide with Examples.pdf
Taming client-server communication
NodeJS and ExpressJS.pdf
ember-socket-guru - common api for websockets providers
How to implement authorization in your backend with AWS IAM
Php & Web Security - PHPXperts 2009
Bt0083 server side programing
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020

Similar to How to use Cypress Intercept to Stub API Responses.pdf (20)

ODP
SCWCD 2. servlet req - resp (cap3 - cap4)
PPT
Java Servlets
PDF
Pixels_Camp
PDF
Express node js
PPTX
SW Security Lec4 Securing architecture.pptx
PPTX
Sherlock Homepage - A detective story about running large web services - NDC ...
PPTX
Design Summit - RESTful API Overview - John Hardy
PPTX
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
PPT
Lecture 2
PPTX
Sherlock Homepage (Maarten Balliauw)
PPTX
Sherlock Homepage - A detective story about running large web services (VISUG...
DOCX
Cypress.docx
PDF
Webinar - 2020-09-23 - Escape the ticketing turmoil with Teleport PagerDuty &...
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
PPTX
Ingesting streaming data for analysis in apache ignite (stream sets theme)
PDF
NGINX Can Do That? Test Drive Your Config File!
PDF
Webservices in SalesForce (part 1)
PPT
Servlet
PPTX
Scaling asp.net websites to millions of users
PPTX
Sherlock Homepage - A detective story about running large web services - WebN...
SCWCD 2. servlet req - resp (cap3 - cap4)
Java Servlets
Pixels_Camp
Express node js
SW Security Lec4 Securing architecture.pptx
Sherlock Homepage - A detective story about running large web services - NDC ...
Design Summit - RESTful API Overview - John Hardy
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
Lecture 2
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage - A detective story about running large web services (VISUG...
Cypress.docx
Webinar - 2020-09-23 - Escape the ticketing turmoil with Teleport PagerDuty &...
SERVLETS (2).pptxintroduction to servlet with all servlets
Ingesting streaming data for analysis in apache ignite (stream sets theme)
NGINX Can Do That? Test Drive Your Config File!
Webservices in SalesForce (part 1)
Servlet
Scaling asp.net websites to millions of users
Sherlock Homepage - A detective story about running large web services - WebN...
Ad

More from Steve Wortham (20)

PDF
Selenium Testing The Complete Step-by-Step Tutorial.pdf
PDF
The SAP Testing A Comprehensive Guide.pdf
PDF
The Ultimate Guide to Salesforce Automation.pdf
PDF
Top AI Testing Tools to Streamline Your Automation Efforts.pdf
PDF
findElement and findElements in Selenium_ Use Cases with Examples.pdf
PDF
Streamlining Enterprise Demands Selecting the Ideal Cloud Test Automation.pdf
PDF
Geolocation Testing for Global Success_ Test from Anywhere.pdf
PDF
The Next Wave of Software Testing_ Trends Shaping 2025.pdf
PDF
Creating an Effective Enterprise Testing Strategy_ Best Practices and Conside...
PDF
How to Inspect Elements on Android Devices.pdf
PDF
GUI Testing_ Best Practices, Tools, and Checklists You Can’t Miss.pdf
PDF
Introducing TestGrid’s Private Device Lab.pdf
PDF
Scriptless Test Automation_ A Complete Guide.pdf
PDF
Top iOS Testing Tools and Frameworks.pdf
PDF
The Test Cases for E-commerce Website.pdf
PDF
Playwright and its Installation Guide.pdf
PDF
A Guide to Codeless Automation on iPhone Devices.pdf
PDF
Understanding DevOps, its benefits, and best practices.pdf
PDF
Boost Your Telecom Testing Strategy_ Steps to Achieve Seamless Connectivity.pdf
PDF
A Complete Step-by-Step Guide to Mobile App Performance Testing.pdf
Selenium Testing The Complete Step-by-Step Tutorial.pdf
The SAP Testing A Comprehensive Guide.pdf
The Ultimate Guide to Salesforce Automation.pdf
Top AI Testing Tools to Streamline Your Automation Efforts.pdf
findElement and findElements in Selenium_ Use Cases with Examples.pdf
Streamlining Enterprise Demands Selecting the Ideal Cloud Test Automation.pdf
Geolocation Testing for Global Success_ Test from Anywhere.pdf
The Next Wave of Software Testing_ Trends Shaping 2025.pdf
Creating an Effective Enterprise Testing Strategy_ Best Practices and Conside...
How to Inspect Elements on Android Devices.pdf
GUI Testing_ Best Practices, Tools, and Checklists You Can’t Miss.pdf
Introducing TestGrid’s Private Device Lab.pdf
Scriptless Test Automation_ A Complete Guide.pdf
Top iOS Testing Tools and Frameworks.pdf
The Test Cases for E-commerce Website.pdf
Playwright and its Installation Guide.pdf
A Guide to Codeless Automation on iPhone Devices.pdf
Understanding DevOps, its benefits, and best practices.pdf
Boost Your Telecom Testing Strategy_ Steps to Achieve Seamless Connectivity.pdf
A Complete Step-by-Step Guide to Mobile App Performance Testing.pdf
Ad

Recently uploaded (20)

PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
WOOl fibre morphology and structure.pdf for textiles
PPTX
TLE Review Electricity (Electricity).pptx
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
Hybrid model detection and classification of lung cancer
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
August Patch Tuesday
PPTX
A Presentation on Artificial Intelligence
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Getting Started with Data Integration: FME Form 101
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PPTX
A Presentation on Touch Screen Technology
PDF
Web App vs Mobile App What Should You Build First.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Programs and apps: productivity, graphics, security and other tools
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
WOOl fibre morphology and structure.pdf for textiles
TLE Review Electricity (Electricity).pptx
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Hindi spoken digit analysis for native and non-native speakers
Hybrid model detection and classification of lung cancer
cloud_computing_Infrastucture_as_cloud_p
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
August Patch Tuesday
A Presentation on Artificial Intelligence
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Getting Started with Data Integration: FME Form 101
Assigned Numbers - 2025 - Bluetooth® Document
Building Integrated photovoltaic BIPV_UPV.pdf
OMC Textile Division Presentation 2021.pptx
Enhancing emotion recognition model for a student engagement use case through...
A Presentation on Touch Screen Technology
Web App vs Mobile App What Should You Build First.pdf

How to use Cypress Intercept to Stub API Responses.pdf

  • 2. How to use Cypress Intercept to Stub API Responses Cypress is a Unique tool it 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 ? Intercept is a fairly new concept in the world of service virtualization, the “cy.intercept()” is a very powerful concept, using this we can monitor all the interaction of the application with the webservices or third party API. During test automation and execution it becomes extra useful as we can control various aspects of applications and its interaction with external API and services.
  • 3. Why 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 which are performing communication between application 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 which were made by 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 are 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.
  • 4. For performing Security testing using Cypress we can do Cross -site scripting testing by which we can simulate user inputs and check if they are getting sanitised for preventing XSS vulnerabilities below is the code snippet which is showing an example for implementing. // 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 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.
  • 5. 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 analyse and collect the 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 most used ways by which we can use Cy.Intercept().
  • 6. 1. 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 fixture file named as ‘inter.json’ cy.intercept('GET', '/api/inters, { fixture: 'inter.json' }).as('getInter'); 2. Modifying responses: We can perform modification 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. Copy cy.intercept('PUT', '/api/users/1', (req) => { req.reply({ statusCode: 200, body: { id: 1, name: 'Updated User' } }); }).as('updateUser'); 3. 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');
  • 7. 4. Aliasing and waiting: After performing an intercept we can use the concept of aliasing using ‘.as()’ for the intercepted request and put a wait contention until it gets completed. cy.intercept('GET', '/api/data').as('getData'); // Perform actions that trigger the GET request cy.wait('@getData'); Prerequisite for Cypress Intercepts? For performing cypress Intercept operation few basic things are required such as cypress installed and working, understanding of network request and responses and commands like (HTTPS,PUT,POST,GET,DELETE). Understanding of java script is also required for performing scripting . Cypress Intercepts implementation Here we are intercepting functionality and setting a response which will be coming from the fixture file. In the below example we are trying to describe how to perform cypress intercept cy.intercept(). Firstly we need a request whether it is GET/PUT/POST and we need to create a fixture file where we will be storing the response which we want to send when the request comes in. In the later part of the code we are using aliasing “.as(‘getPosts’)” the request that it can be used further. After that we will be visiting the web application and performing an action which later creates a GET request and then we wait for it to get intercepted and then we send the response which we have stored inside the fixture.
  • 8. After that we verify the response assertion, whether the response contains expected response code or elements in the body. // my_test.spec.js describe('Intercepting Network Requests', () => { it('should intercept a GET request', () => { // Intercept a GET request to a specific URL cy.intercept('GET', '/api/posts', { fixture: 'posts.json' }).as('getPosts'); // Visit the page that triggers the GET request cy.visit('/'); // Perform actions that trigger the GET request, e.g., click a button // Wait for the intercepted request to complete cy.wait('@getPosts').then((interception) => { // Verify the response or perform assertions expect(interception.response.statusCode).to.equal(200); expect(interception.response.body).to.have.length(3); // Assuming 'posts.json' contains an array of 3 posts }); }); }); Real time Implementation:
  • 9. Here in this example we are setting the ERP details in fixtures so that when user looks for particular ERP and in real time it is not available with the API or we are not getting response from API, That time we can use the response stored inside fixtures which contains details of ERP(name, ID and other completion status). Once a request is submitted the response is supplied back and the user can complete the test with this data. cy.wait('@GetUserDetails').then((response) => { cy.log(response); }); .its('response.body.data.login') .should('have.property', 'id') .and('have.property', 'token'); Mocking example cy.intercept('POST', '/graphql', (req) => { if (req.body.operationName === 'GetErps') { req.reply((res) => { res.send({ data: { erps: [ { id: 'MyCustomERP1', name: 'MyCustomERP1', standard: true, pipelineId: null, extractType: ['REPORT'], auditFirm: null, __typename: 'Erp', }, ], }, }); });
  • 10. } }); .as('GetErps'); }); Conclusion: Cypress comes with a lot of libraries and functionalities, using which we can perform End to End automation with great efficiency and speed. Implementation of new concepts and techniques is fairly easy and achievable. While performing Intercept it gives us a great amount of flexibility to test the application in all possible perspectives, it reduces the dependency of third party API’s and helps us to run our test cases smoothly. Source: This article was originally published at testgrid.io