Get different response from same URL

70 Views Asked by At

I am working on a React app, where I am using Cypress for testing. My requirements are to compare payload which we are sending in our app and which the ecosystem (DB/backend) has. By using 'Intercept' we can get the request and response from the app, but the issue is we are having same URL with different payload, so every time it's taking only one API and passing the results. Need to get different request and response from APIs. Can someone help with this?

cy.intercept({ method: 'POST', url: Cypress.env("URL") }).as('call')
cy.wait('@call').then(({ request, response }) => {
  console.log(request.body,"Hey")
  // console.log(response.body,"body")
  //get dynamically data from json file
  cy.fixture(`kpiId${request.body.kpiId}.json`).then((jsonData) => {
    // Access and use jsonData here
    let json = jsonData
    console.log(json,"jsonnnnn")
    console.log(`kpiId${request.body.kpiId}.json`,jsonData)
    expect(request.body).to.deep.eq(jsonData)
  });
})
1

There are 1 best solutions below

2
TesterDick On

The code looks ok for handling different "payloads" i.e differentiating the response by KPI value in the body.

It will only catch the first KPI if you only have one cy.wait('@call').

The way it works is:

  • one cy.intercept(...).as('call') to listen to all calls to the URL-to-be-matched
  • multiple cy.wait('@call'), one per call that occurs.
cy.intercept(...).as('call')

function callHandler = ({ request, response }) => {
  cy.fixture(`kpiId${request.body.kpiId}.json`).then(json => {    
    expect(request.body).to.deep.eq(jsonData)
  })
}

cy.visit(react-app-url)

cy.wait('@call').then(callHandler)  // first KPI
cy.wait('@call').then(callHandler)  // second KPI
cy.wait('@call').then(callHandler)  // third KPI

If the app has a regression error and only sends two KPI POST, the third cy.wait('@call') will alert you to the fact.