Cypress Request/Response Modification with routeHandler

Profile picture for user arilio666

This article will show how to modify a request/response with a route handler.

Routehandler is the last argument to modify the outgoing or stub request/response or make assertions.

cy.intercept('/endpoint', (req) => {
})

We can do several things with the intercepted request:

  • Modify and make assertions with the body, URL, method, etc.
  • Stub responses without having to deal with the actual backend.
  • Pass requests and make assertions or modifications.
  • Attaching listeners to various events.

Assert


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


           req.continue((res) => {
             expect(res.statusCode).to.equal(200)
          });
         }).as('interUrl');
  • With this, we are asserting the response code to 200.

Send Payload:

cy.visit('https://reqres.in/')
       cy.intercept({
           method: 'POST', 
           url: 'https://reqres.in/api/users',
           middleware: false
       },(req) => {
           req.continue((res) => {
               res.send({ "name":"JohnWick",
               "job":"Assasin"
               })
           })
       }).as('successfulAction')
  • Here it is used to send the payload to the API site using the POST method.

Add Header:

cy.intercept('POST', '/users', (req) => {
 req.headers['Hello'] = 'added by naruto'
})
  • Here it is used to modify the header and add a custom header or even modify the existing header.

Conclusion:

These are some ways we can play around with route handlers using intercept in cypress.