如何在Cypress中存储请求的响应



我有以下代码

cy.intercept('GET', Cypress.env('activationCode')).as('getActivationCode')
let validationCode;
cy.request('GET', Cypress.env('activationCode'))
.then( ({ body }) => {
validationCode = body
console.log(body);
// this have the value
})
cy.wait('@getActivationCode')
console.log(validationCode)
// this is undefined

我需要从get请求中接收一个变量来填写表单,但我不知道如何期望它接收值,以便继续执行。我不想在请求的时间内进行编码。

console.log(validationCode)这是未定义的,因为非柏树命令在柏树命令之前运行。因此,在用任何值更新validationCode之前,都要打印它。为了避免这种情况,我们cy.log()。此外,柏树建议使用变量的方式是使用别名。

cy.intercept('GET', Cypress.env('activationCode')).as('getActivationCode')
cy.request('GET', Cypress.env('activationCode')).then(({body}) => {
cy.wrap(body).as('responseBody') //save response body using alias
console.log(body)
// this have the value
})
cy.wait('@getActivationCode')
cy.get('@responseBody').then((responseBody) => {
cy.log(responseBody) //prints the response body
})

如果你想使用console.log,你可以这样做:

let validationCode
cy.request('GET', Cypress.env('activationCode'))
.then(({body}) => {
validationCode = body
console.log(body)
// this have the value
})
.then(() => {
cy.wait('@getActivationCode')
console.log(body)
})

Cypress命令是异步的,所以在混合异步和同步代码时应该小心。

通过使用.its()命令,您可以从请求中轻松访问某个属性。

cy.intercept('GET', Cypress.env('activationCode'))
.its('response.body.variableIWant') // you'll need drill down to your specific variable you want
.as('variableIWant')
// some other code
cy.get('@variableIWant')

.then()的另一种使用方法

cy.intercept('GET', Cypress.env('activationCode'))
.its('response')
.then( resp = >{
// some code to get variable you want
return variableIWant //this will become new subject for cy commands
})
.as('variableIWant')
// some other code
cy.get('@variableIWant')

另一种选择,使用组合before()function().this

before(function() {    
cy.request('GET', Cypress.env('activationCode'))
.then( ({ body }) => {
return body
})
.as('validationCode')   // puts body into this.validationCode
})
it('tests the validationCode', function() {
console.log(this.validationCode)
})
it('another test of validationCode', function() {
console.log(this.validationCode)
})

您应该查看验证请求修改

无法使用cy.request((调试cy.entercept((!Cypress只拦截前端应用程序发出的请求。

这意味着cy.request()不会激发cy.intercept()

最新更新