我有以下案例:
用户上传文件后,屏幕上会出现一个表格报告。问题是:表格不会自动出现,用户需要重新加载页面,如果文件已经处理,则表格显示在屏幕上,如果仍在处理,用户需要稍等一下并再次重新加载。
如何在不使用 cy.wait() 等待任意时间的情况下完成此任务。我想是这样的:
cy.reload().should(() => {
expect(document.querySelectorAll('table')).to.not.be.empty
})
Run Code Online (Sandbox Code Playgroud)
但没有用
如果should()断言失败,Cypress 只会重复某些命令。正如您所看到的,reload()它不是其中之一。
我建议使用递归来实现重复的重新加载周期。这是一个例子:
let remainingAttempts = 30;
function waitUntilTableExists() {
let $table = Cypress.$('table');
if ($table.length) {
// At least one table tag was found.
// Return a jQuery object.
return $table;
}
if (--remainingAttempts) {
cy.log('Table not found yet. Remaining attempts: ' + remainingAttempts);
// Requesting the page to reload (F5)
cy.reload();
// Wait a second for the server to respond and the DOM to be present.
return cy.wait(1000).then(() => {
return waitUntilTableExists();
});
}
throw Error('Table was not found.');
}
waitUntilTableExists().then($table => {
cy.log('table: ' + $table.text());
});
Run Code Online (Sandbox Code Playgroud)
您可能会想使用fororwhile循环,但这不适用于 Cypress。这是因为大多数命令不会立即执行。相反,命令是异步的。