如何通过函数返回 cy.request 的响应

2023-12-11

我正在尝试使用以下函数传递 API 请求的结果:

Add(someName) {
        cy.request ({
            method: 'POST',
            url: someURL,
            body: {
                name: someName
            }
        }).then(function(response){
            return response
        })
    }

然而,当我尝试调用此函数时,它没有给我响应的内容(它给我未定义)。我认为这可能与异步性(如果这是一个词)或对象的范围有关,因此尝试为响应别名或在函数外部定义一个对象(然后将响应分配给该对象),而不需要运气好的话。


你只需要一个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 
}

返回值类型是 Chainer(与所有 Cypress 命令的类型相同),因此您must use a .then() on it

myPO.Add('myName').then(body => ...

你不需要.then() after cy.request()

如果您想要完整的回复,

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

Awaiting

const response = await myPO.Add('myName')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过函数返回 cy.request 的响应 的相关文章

随机推荐