Home > Software engineering >  I am unable to find any solution to pass value of API response to new file and use that object value
I am unable to find any solution to pass value of API response to new file and use that object value

Time:09-03

I have 2 files:

  1. Test Specs
  2. API layer (in which all API's are written like cy.request(). I am returning API response from here

I need to use the response of API in my test spec. But when I try to use the response I am getting undefined

That is how I returning my response

testFun() {
    cy.request({
      method: "GET",
      url: `${this.objectFactory.url}/api-v7/listings/`,
      headers: {
        accept: "application/json",
        Authorization: this.objectFactory.authorization,
        cookie: this.objectFactory.cookie,
      },
    }).then((response) => {
      
          return response;
        }
      });
    });
  }

And in spec file, I am calling this function and getting undefined

CodePudding user response:

Can you try adding a return before the cy.request command?


    testFun() {
        return cy.request({
          method: "GET",
          url: `${this.objectFactory.url}/api-v7/listings/`,
          headers: {
            accept: "application/json",
            Authorization: this.objectFactory.authorization,
            cookie: this.objectFactory.cookie,
          },
        });
      }


      # then do
      testFun().then((response) => { do something with response });

CodePudding user response:

Return the request from the function, you don't need the .then() added.

testFun() {
    return cy.request({
      method: "GET",
      url: `${this.objectFactory.url}/api-v7/listings/`,
      headers: {
        accept: "application/json",
        Authorization: this.objectFactory.authorization,
        cookie: this.objectFactory.cookie,
      },
    })
  }

Use it in the test with a .then()

testFun().then(response => {
  // assert response here
})
  • Related