jay*_*esh 7 javascript testing integration-testing cypress
我有一个自定义的 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");
});
});
});
Run Code Online (Sandbox Code Playgroud)
测试
describe("Summary Page", () => {
it("my demo test", () => {
console.log("before command runs");
cy.testCommand();
console.log("after command runs");
});
});
Run Code Online (Sandbox Code Playgroud)
实际结果
before command runs
after command runs
success
Run Code Online (Sandbox Code Playgroud)
所需结果
before command runs
success
after command runs
Run Code Online (Sandbox Code Playgroud)
如您所见,输出after command runs将在命令完成之前运行
在继续测试之前有什么方法可以等待命令完成
无论您的自定义命令是否返回 cypress 链,您都可以在命令将其包装在回调中之后then运行代码:
describe('Summary Page', () => {
it('my demo test', () => {
console.log('before command runs')
cy.testCommand()
cy.then(() => {
console.log('after command runs')
})
})
})
Run Code Online (Sandbox Code Playgroud)
至于使用async/await,Cypress默认不支持async/await,请参阅这个问题和里面的长篇讨论。
要减少回调次数,您可以尝试cypress-promise或cypress-thenify库。然而,它们每个都有其自身的局限性。
这是因为非 cypress 命令异步运行,这意味着它不一定按写入的顺序运行命令。为了解决这个问题,你可以使用then(),类似:
describe('Summary Page', () => {
it('my demo test', () => {
console.log('before command runs')
cy.testCommand().then(() => {
console.log('after command runs')
})
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11737 次 |
| 最近记录: |