在 Cypress 中使用 API 调用时如何避免 .then() 嵌套?

问题描述 投票:0回答:2

与我的团队一起,我们正在尝试找到一种更具可读性的方法来处理 Cypress 中的依赖 API 调用。现在我们有一些像这样的代码:

// nested code
      cy.request('GET', myUrl).its('body').then(res => {
        cy.request('GET', res).its('body').then(subRes => {
          cy.request('GET', subRes).its('body').then(subSubRes => {
            expect(subSubRes, myMessage).to.eq(myEvaluation);
          })
        })
      })

我们也考虑过这个解决方案,但我认为我们在可读性方面并没有获得太多。

// less nested code?
      let response;
      let subResponse;
      cy.request('GET', myUrl).its('body').then(res => {
        response = res;
      })
      
      cy.then(() => {
        cy.request('GET', response).its('body').then(subRes => {
          subResponse = subRes;
        })
      })

      cy.then(() => {
        cy.request('GET', subResponse).its('body').then(subSubRes => {
          expect(subSubRes, myMessage).to.eq(myEvaluation);
        })
      })

您有什么想法可以在不进入金字塔的情况下处理这种逻辑吗? 预先感谢!

javascript automated-tests cypress e2e-testing
2个回答
12
投票

类似的东西

cy.request('GET', myUrl).its('body')
    .then(res => cy.request('GET', res).its('body'))
    .then(subRes => cy.request('GET', subRes).its('body'))
    .then(subSubRes => {
        expect(subSubRes, myMessage).to.eq(myEvaluation);
    });

应该可以。


-4
投票

请使用 Promise 解析:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

cy.request('GET', myUrl).its('body')
    .then(res => cy.request('GET', res).its('body'))
    .then(res => cy.request('GET', res).its('body'))
    .then(res => {
        expect(res, myMessage).to.eq(myEvaluation);
    });
}

© www.soinside.com 2019 - 2024. All rights reserved.