【问题标题】:How do I return the response from a cy.request through a function如何通过函数从 cy.request 返回响应
【发布时间】:2021-10-26 09:43:40
【问题描述】:
我正在尝试使用以下函数传递 API 请求的结果:
Add(someName)
{
cy.request ({
method: 'POST',
url: someURL,
body: {
name: someName
}
}).then(function(response){
return response
})
}
但是,当我尝试调用此函数时,它并没有给我响应的内容(它给了我未定义的内容)。我认为这可能与异步性(如果这是一个词)或对象的范围有关,因此尝试对响应进行别名处理或在函数之外定义一个对象(然后将响应分配给该对象),没有祝你好运。
【问题讨论】:
标签:
javascript
asynchronous
request
return
cypress
【解决方案1】:
您只需要在cy.request() 通话中使用return。
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
}
返回值类型是 Chainer(与所有 Cypress 命令的类型相同),因此您必须在其上使用 .then()
myPO.Add('myName').then(body => ...
cy.request() 之后不需要.then()
如果您想要完整的回复,
Add(someName) {
return cy.request ({...}) // don't need a .then() after this
// to return full response
}
如何等待结果
如果您想等待结果,请使用Cypress.Promise,如图所示here
Add(someName) {
return new Cypress.Promise((resolve, reject) => {
cy.request ({...})
.then(response => resolve(response))
})
}
等待
const response = await myPO.Add('myName')
【解决方案2】:
你应该尝试在你的函数中返回一些东西:
Add(someName)
{
return cy.request ({
method: 'POST',
url: someURL,
body: {
name: someName
}
}).then(function(response){
return response
})
}
然后获取返回的值:
Add('val').then((data) => {console.log(data)})