我正在使用Cypress测试一个数据导出页面,该页面需要几分钟才能生成一个导出。页面不会动态更新,所以我需要让Cypress重新加载页面,直到状态显示为已完成为止。我查看了Cypress文档,找不到一种检查元素是否存在的方法,如果不存在,就不会抛出异常。
我尝试使用jQuery,但这导致了一个无限循环:
describe('test reloading', function () {
it('testSelector reload', function () {
cy.visit('https://docs.cypress.io/api/utilities/$.html#Usage');
let found = false;
while (!found) {
const nonExistent = Cypress.$('.fake-selector');
if (!nonExistent.length) {
cy.reload();
} else {
found = true;
}
}
});
});发布于 2019-01-16 14:09:46
你可以试试这段代码。您的元素不可用,因此导致无限循环。你需要在一段时间后从循环中跳出来。
describe('test reloading', function() {
it('testSelector reload', function() {
cy.visit('https://docs.cypress.io/api/utilities/$.html#Usage');
let found = false;
let count = 0;
while (!found) {
const nonExistent = Cypress.$('.fake-selector');
if (!nonExistent.length) {
cy.reload();
found = false;
count = count + 1;
cy.wait(1000);
if (count == 30) {
found = true;
cy.log('Element not found after 30 seconds..Exit from loop!!!');
}
} else {
found = true;
}
}
});
});发布于 2020-12-05 00:06:45
我不能推荐Cypress中的while循环,因为您混合了同步语句(如Cypress.$() )和异步语句(如cy.reload() )。
为了让Cypress.$()获取新元素,它需要一个新的上下文,比如在.then()或.should()中。
我建议使用递归来实现重复的重新加载周期。下面是一个示例:
it('testSelector reload', function() {
let remainingAttempts = 30;
function waitUntilSelectorExists() {
let $el = Cypress.$('.fake-selector');
if ($el.length) {
// At least one tag was found.
// Return a jQuery object.
return $el;
}
if (--remainingAttempts) {
cy.log('Selector 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 updated.
return cy.wait(1000).then(() => {
return waitUntilSelectorExists();
});
}
throw Error('Selector was not found.');
}
waitUntilSelectorExists().then($el => {
cy.log('$el contains this text: ' + $el.text());
});
});为了避免为现在可能不存在的元素抛出错误(但稍后),解决方案是对父元素进行get(),然后尝试对子元素进行find():
cy.get('#parent_of_sometimesMissing').then($element => {
if ($element.find('#sometimesMissing').length > 0) {
....
}
});https://stackoverflow.com/questions/54216559
复制相似问题