我认为Cypress中的return
语句不会像同步JavaScript那样退出循环或函数,因为它表现得有所不同。
以下是添加的代码:
it("Test to stop a FOR loop", function () {
cy.visit("https://docs.cypress.io/guides/overview/why-cypress");
function iterate(i) {
if (i < 5) {
cy.wait(1000);
cy.url().then((url) => {
cy.log(`**${url}**`);
if (url.includes("api")) {
// 停止递归
return;
}
if (url.includes("overview")) {
cy.log("**The URL includes OVERVIEW**");
cy.get('[href="/api/table-of-contents"]')
.click()
.then(() => {
iterate(i + 1); // 继续下一次迭代
});
} else if (url.includes("plugins")) {
cy.log("**The URL includes PLUGINS**");
cy.get(".navbar__inner > :nth-child(1) > :nth-child(3)")
.click()
.then(() => {
iterate(i + 1); // 继续下一次迭代
});
} else {
iterate(i + 1); // 继续下一次迭代
}
});
}
}
iterate(0); // 以初始索引开始递归
});
在这段代码中,iterate
函数为每次迭代递归调用。
这确保了每次迭代都会等待异步Cypress命令完成后再进行下一次迭代。
当满足期望条件 (url.includes('api'))
时,递归将停止。