Muneeb
Muneeb

Reputation: 111

In cypress Returning Api reponse to another function is displaying undefined

I'm calling a function GetApiResponse() from CallApi() which is returning an object of Api response. If I'm printing that response in GetApiResponse() in display complete object in console. But i'm passing this to 'passstatus' variable in CallApi function. But here it's displaying undefined. I tried JSON.Stringyfy() stuff but it didn't work for me.

I want to use that reponse from GetApiResponse() function in ApiCall function.

it("ApiCall", function(){

        function testCallBack(){

            var passstatus=GetApiResponse(testData2)
            setTimeout(()=>{
            console.log(passstatus) //This returns undefined
           expect(passstatus.status).to.equal("pass")
            },15000);
        
        }

      testCallBack();


})

 function GetApiResponse(testData2){
      cy.request({
          method: "GET",
          url: `https://test.orders.com//admin/api/2022-01/orders.json?name=%23${testData2.orderId}&status=any`,
          headers: {
            Accept: 'application/json',
            "Content-Type": 'application/json',
            "Access-Token": "XXXXXXXXXXX"
          }
        }).then(response =>{
            const jsonData = response.body.orders[0];
            console.log(jsonData)
            return jsonData;
        })
}

Upvotes: 1

Views: 965

Answers (1)

Fody
Fody

Reputation: 32044

Return the outer request, otherwise the inner return jsonData is ignored

function GetApiResponse(testData2) {
  return cy.request({
           ...
         }).then(response => {
           return response.body.orders[0];
        })
}

It's asynchronous, so use with .then()

GetApiResponse(testData2).then(passstatus => {
  ... // use passStatus here
})

Or use an alias

function GetApiResponse(testData2) {
  cy.request({
    ...
  }).then(response => {
    return response.body.orders[0];
  })
  .as('passstatus')    // store to an alias
}
GetApiResponse(testData2)
cy.get('@passstatus').then(passstatus => {
  ... // use passStatus here
})
        

Upvotes: 1

Related Questions