首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cypress:检查元素是否存在,无一例外

问Cypress:检查元素是否存在,无一例外
EN

Stack Overflow用户
提问于 2019-01-16 11:55:50
回答 2查看 9.2K关注 0票数 5

我正在使用Cypress测试一个数据导出页面,该页面需要几分钟才能生成一个导出。页面不会动态更新,所以我需要让Cypress重新加载页面,直到状态显示为已完成为止。我查看了Cypress文档,找不到一种检查元素是否存在的方法,如果不存在,就不会抛出异常。

我尝试使用jQuery,但这导致了一个无限循环:

代码语言:javascript
复制
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;
      }
    }
  });
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-16 14:09:46

你可以试试这段代码。您的元素不可用,因此导致无限循环。你需要在一段时间后从循环中跳出来。

代码语言:javascript
复制
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;
      }
    }
  });
});
票数 5
EN

Stack Overflow用户

发布于 2020-12-05 00:06:45

我不能推荐Cypress中的while循环,因为您混合了同步语句(如Cypress.$() )和异步语句(如cy.reload() )。

为了让Cypress.$()获取新元素,它需要一个新的上下文,比如在.then()或.should()中。

我建议使用递归来实现重复的重新加载周期。下面是一个示例:

代码语言:javascript
复制
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():

代码语言:javascript
复制
cy.get('#parent_of_sometimesMissing').then($element => {
  if ($element.find('#sometimesMissing').length > 0) {
    ....
  }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54216559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档