Cypress Intercepting a Response

Profile picture for user arilio666

In this article, we will see an exciting topic on how to intercept response in cypress.

Syntax:


       cy.intercept('GET', 'url', (req) => {
          //modify url


           req.continue((res) => {
             //play with response
           });
         });
  • We will modify the URL and check the response using the intercept to pass in the URL for intercepting.
  • For this, we will be using the reqres site.
  • Here is the URL with id=9.
  • We will list all users and then intercept with this id and get the response whether the id=9 page is loaded.
describe('Intercepting Gorestapi',()=>{

   it('Intercepting Route of users',()=>{
       cy.visit('https://reqres.in/')
       cy.intercept('GET', 'https://reqres.in/api/users?page=2', (req) => {
           req.url='https://reqres.in/api/users?id=9'


           req.continue((res) => {
             expect(res.statusCode).to.equal(200)
\            });
         }).as('interUrl');
       cy.xpath('//span[@class="url"]').click({force: true})
       cy.wait('@interUrl')

  
   })
})
  • Using the req object from intercept, we modified it to the required URL.
  • With the req object, we create another callback object res and expect the response to be 200.
  • We can see here that the id=9 page has been loaded, and the response code is also 200.

Conclusion:

This is how we can play around with intercepting responses.