1

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;
        })
}

Muneeb
  • 67
  • 1
  • 7

1 Answers1

1

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
})
        
Fody
  • 23,754
  • 3
  • 20
  • 37
  • Thankyou So much Fody. For GetApiResponse().Then() i will still getting issue that then can't read undefined properties but Alias solution really worked for me – Muneeb Mar 01 '22 at 12:45
  • Good job I gave two answers :). `.then()` should also work, it's worth playing around until it works because it's useful technique when you use functions to encapsulate commands. – Fody Mar 01 '22 at 12:52
  • BTW in your comment you show `.Then()` instead of `.then()` but I assume it's a typo? – Fody Mar 01 '22 at 12:53