How to use Cypress Intercept to Stub API Responses

how to use cypress intercept

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 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.

mobile app automation

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Tweet
Share
Share
Pin