我有一個自定義的 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將在命令完成之前運行
在繼續測驗之前有什么方法可以等待命令完成
uj5u.com熱心網友回復:
無論您的自定義命令是否回傳柏樹鏈,您都可以在將其包裝在回呼中的命令之后運行代碼: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-promise或cypress-thenify庫。然而,他們每個人都有自己的局限性。
uj5u.com熱心網友回復:
這是因為非 cypress 命令異步運行,這意味著它不一定會按寫入的順序運行命令。要解決這個問題,您可以使用then(),例如:
describe('Summary Page', () => {
it('my demo test', () => {
console.log('before command runs')
cy.testCommand().then(() => {
console.log('after command runs')
})
})
})
uj5u.com熱心網友回復:
如果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");
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422900.html
標籤:
