I am trying to pass the result of an API request using the following function:
Add(someName)
{
cy.request ({
method: 'POST',
url: someURL,
body: {
name: someName
}
}).then(function(response){
return response
})
}
When I try to call this function however, it does not give me the content of the response (it gives me Undefined). I thought this probably has something to do with either asynchronosity (if that is a word),or the scope of the object and therefore tried aliasing the response or defining an object outside of the function (then assigning the response to that object), without any luck.
You just need a return on the cy.request() call.
Add(someName) {
return cy.request ({...})
.then(function(response) {
return response.body // maps the response to it's body
}) // so return value of function is response.body
}
The return value type is a Chainer (the same type as all Cypress commands) so you must use a .then() on it
myPO.Add('myName').then(body => ...
You don't need .then() after cy.request()
If you want the full response,
Add(someName) {
return cy.request ({...}) // don't need a .then() after this
// to return full response
}
How to await the result
If you want to await the result, use a Cypress.Promise as shown here
Add(someName) {
return new Cypress.Promise((resolve, reject) => {
cy.request ({...})
.then(response => resolve(response))
})
}
Awaiting
const response = await myPO.Add('myName')
You should try returning something in your function:
Add(someName)
{
return cy.request ({
method: 'POST',
url: someURL,
body: {
name: someName
}
}).then(function(response){
return response
})
}
And then get the value returned:
Add('val').then((data) => {console.log(data)})