26.09.2024 Views

How to use Cypress Intercept to Stub API Responses

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.

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.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!