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

CypressIO make a request then use the response to pass to another function to call another request, wrap inside a re-usable function

所以我遇到的问题是我希望能够调用模块函数,然后调用 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.request,例如 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();
}

您可以使用 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)