Cypress:检查元素是否存在,无异常

jez*_*nag 5 cypress

我正在使用 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;
      }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

Kun*_*duK 5

你可以试试这个代码。您的元素不可用,从而导致无限循环。您需要在一定时间后跳出循环。

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;
      }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)