Cypress - Intercept Identical API Calls with different payload

160 Views Asked by At

I have two identical API requests but different payloads. For example

  1. Request URL: http://localhost:8000/getdata/

Request Method: POST

Request body: { dataCategory:"Hardware" }

  1. Request URL: http://localhost:8000/getdata/

Request Method: POST

Request body: { dataCategory:"Software" }

My current code -

cy.intercept({
    method: 'POST',
    url: '/getData',
   
}).as('apiCheck');

cy.get(desktopElements.SomeElement).click();
cy.wait('@apiCheck').then((interception) => {
    assert.isNotNull(interception.request.body.dataCategory, 'Request');
})

I know for a fact that I cannot include dataCategory inside the intercept method. Is there a way to achieve this?

1

There are 1 best solutions below

0
Aladin Spaz On

If you want the intercept to be specific to the value of dataCategory, add a dynamic alias - ref documentation Aliasing individual requests

cy.intercept('POST', '/getData', (req) => {

  if (req.body.dataCategory === 'Hardware' ) {
    req.alias = 'hardware'
  }
  if (req.body.dataCategory === 'Software' ) {
    req.alias = 'software'
  }

  // or simply
  req.alias = req.body.dataCategory

});

cy.get(desktopElements.SomeElement).click()

cy.wait('@software').then((interception) => {
  assert(interception.request.body.dataCategory === 'Software', 'Request is Software');
})