在 commands.js 中编写函数时避免使用金字塔

Avoid a pyramid while writing a function in commands.js

做这个例子时如何避免金字塔?

Cypress.Commands.add("test", () => {
    
// first request
    cy.request("POST", url1)
        .its("body")
        .then((response) => {
            let userId = response.user._id

            // second request
            cy.request("POST", url2)
                .its("body")
                .then((response) => {
                    let adminAuth = response.accessToken

                    // third request
                    cy.request({
                        method: "POST",
                        url: url
                        headers: { "x-access-token": adminAuth },
                        body: { user: userId }

我觉得像这样在 then() 中嵌套是非常低效的。

您可以使用别名来保存该值,然后使用 this. 访问它。类似于:

// first request
cy.request("POST", url1)
  .its("body")
  .then((response) => {
    cy.wrap(response.user._id).as('userId')
  })

// second request
cy.request("POST", url2)
  .its("body")
  .then((response) => {
    cy.wrap(response.accessToken).as('adminAuth')
  })

// third request
cy.request({
  method: "POST",
  url: url,
  headers: {
    "x-access-token": this.adminAuth
  },
  body: {
    user: this.userId
  }
})

我很确定 Alapan 的答案不会起作用,因为您无法在定义它的同一延续中获得 cypress 变量值。此时尚未计算变量(它不是同步的)。 所以你可以这样走:

// first request
cy.request("POST", url1)
  .its("body")
  .then((response) => {
    cy.wrap(response.user._id).as('userId')
  })

// second request
cy.request("POST", url2)
  .its("body")
  .then((response) => {
    cy.wrap(response.accessToken).as('adminAuth')
  })

// accessing the variables inside a then block to let Cypress to compute them
cy.wrap("").then(function() {
// third request
  cy.request({
    method: "POST",
    url: url,
    headers: {
      "x-access-token": this.adminAuth
    },
    body: {
      user: this.userId
    }
  })
})