0

我有一个自定义的 cypress 命令,它执行一些异步任务,并且根据命令的结果,我想执行一些断言

但问题是调用命令后的测试要么在命令完成之前运行,要么有错误的值。

下面是我的代码

命令

Cypress.Commands.add("testCommand", () => {
    cy.request("http://localhost:3000/testApi").then(({ body }) => {
        cy.request(`http://localhost:3000/testApi${body.query}`).then(() => {
            console.log("success");
        });
    });
});

测试

describe("Summary Page", () => {
    it("my demo test", () => {
        console.log("before command runs");

        cy.testCommand();

        console.log("after command runs");
    });
});

实际结果

before command runs
after command runs
success

所需结果

before command runs
success
after command runs

如您所见,输出after command runs将在命令完成之前运行

在继续测试之前有什么方法可以等待命令完成

4

5 回答 5

1

无论您的自定义命令是否返回柏树链,您都可以在将其包装在回调中的命令之后运行代码:then

describe('Summary Page', () => {
  it('my demo test', () => {
    console.log('before command runs')
    cy.testCommand()
    cy.then(() => {
      console.log('after command runs')
    })
  })
})

至于使用async/await,Cypress 默认不支持 async/await,请看这个issue和里面的长篇讨论。

要减少回调次数,您可以尝试cypress-promisecypress-thenify库。然而,他们每个人都有自己的局限性。

于 2022-01-27T10:57:09.153 回答
0

除了上面的答案,您还可以使用 wait() 并执行同步操作
describe("Summary Page", () => {

it("my demo test", () => {
    console.log("before command runs");

    cy.testCommand()as('getCommand');
    cy.wait('@getCommand').then((interception) => {
    console.log("after command runs");
   })  
});

有关更多详细信息,请参阅: https ://docs.cypress.io/api/commands/wait#Alias

于 2022-01-31T17:33:06.873 回答
0

这是因为非 cypress 命令异步运行,这意味着它不一定会按写入的顺序运行命令。要解决这个问题,您可以使用then(),例如:

describe('Summary Page', () => {
  it('my demo test', () => {
    console.log('before command runs')
    cy.testCommand().then(() => {
      console.log('after command runs')
    })
  })
})
于 2022-01-26T14:14:05.743 回答
0

如果console.log()没有必要,那么您可以替换为cy.log(),这将记录到测试运行器。这样你就可以在不改变太多代码的情况下在确切的位置进行替换。

命令

Cypress.Commands.add("testCommand", () => {
    cy.request("http://localhost:3000/testApi").then(({ body }) => {
        cy.request(`http://localhost:3000/testApi${body.query}`).then(() => {
            // you may want to add some assertion here, maybe expected status code
            cy.log("success");
        });
    });
});

测试

describe("Summary Page", () => {
    it("my demo test", () => {
        cy.log("before command runs");
        cy.testCommand();
        cy.log("after command runs");
    });
});
于 2022-01-26T16:13:38.470 回答
0

尝试这样的事情

  Cypress.Commands.add("testCommand", () => {
    cy.request("http://localhost:3000/testApi").then(({ body }) => {      
      cy.request(
        `http://localhost:3000/testApi${body.query}`
      ).then(() => { console.log("success"); });
    }).as('myRequest')
  
    cy.wait(
      '@myRequest', {timeout:30000}
    ).its('response.statusCode').should('eq', '200')
  });
于 2022-01-31T14:00:27.840 回答