【问题标题】:Avoid a pyramid while writing a function in commands.js在 commands.js 中编写函数时避免金字塔
【发布时间】:2021-12-01 20:18:42
【问题描述】:

在做类似这个例子的时候如何避免金字塔?

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() 中是非常无用的。

【问题讨论】:

    标签: cypress


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用别名来保存该值,然后使用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
        }
      })
      

      【讨论】:

        猜你喜欢
        • 2016-10-14
        • 1970-01-01
        • 2021-10-03
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 2023-04-09
        • 2019-05-17
        • 1970-01-01
        相关资源
        最近更新 更多