为了账号安全,请及时绑定邮箱和手机立即绑定

CypressIO 发出请求,然后使用响应传递给另一个函数来调用另一个请求,包装在可重用函数中

CypressIO 发出请求,然后使用响应传递给另一个函数来调用另一个请求,包装在可重用函数中

GCT1015 2023-07-29 15:31:24
所以我遇到的问题是我希望能够调用一个模块函数,然后调用 cy.request() 获取响应并以一种很好的方式将其提供给另一个 cy.request() 。我想让这段代码变得更好:Cypress.Commands.add('createUser', (user) => {  cy.request({  method: 'POST',  url: 'https://www.example.com/tokens',  body: {    email: 'admin_username',    password: 'admin_password' }}).then((resp) => {   cy.request({     method: 'POST',     url: 'https://www.example.com/users',     headers: ({ Authorization: 'Bearer ' + resp.body.token }),     body: user  })})})我想在自己的函数中拥有两个 cy.requests,例如 getAuthToken() 和 createUser(),这样我可以将其包装在 Cypress.Command 中,或者只是一个模块函数并在测试文件中调用const seedUser = (userObject) => {             getAuthToken().then((token) => {                 return createUser(token); //where this would return the created user.             }                }然后在测试文件中像这样使用before(()=>{    let user =  seedUser(); //or let user = cy.seedUser();}
查看完整描述

1 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

您可以使用cy.wrap()来包装第一个请求的响应,然后您可以在任何地方使用它。

自定义命令:

Cypress.Commands.add('getAuthToken', () => {

    cy.request({

        method: 'POST',

        url: 'https://www.example.com/tokens',

        body: {

            email: 'admin_username',

            password: 'admin_password'

        }

    }).then((response) => {

        cy.wrap(response).as('getAuthTokenResponse')

    })

})



Cypress.Commands.add('createUser', (user) => {

    cy.get('@getAuthTokenResponse').then((resp) => {

        cy.request({

            method: 'POST',

            url: 'https://www.example.com/users',

            headers: ({ Authorization: 'Bearer ' + resp.token }),

            body: user

        })

    })

})

在您的测试文件中,您只需添加:


cy.getAuthToken()

cy.createUser(user)


查看完整回答
反对 回复 2023-07-29
  • 1 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信