最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何在 cypress 测试中避免 cy.wait()

网站源码admin33浏览0评论

如何在 cypress 测试中避免 cy.wait()

如何在 cypress 测试中避免 cy.wait()

嗨,我是赛普拉斯的新手,我尽量避免在我的测试中使用
wait()
功能..


我知道,根据官方文档,Cypress 是异步工作的,我们不需要使用

wait()
函数,尤其是
visit()
命令处理它,因为它加载页面然后继续移动。

在我的测试用例中,我想做 2 件导致问题的主要事情:

  1. 打开下拉菜单(在左侧导航菜单上,有 5 个菜单,我想要第二个
  2. 点击一个选项转到另一个页面
it("clicks on the 'Front End' and navigates to the correct page", () => {
  visit(path, {
    timeout: 120000,
    pageLoadTimeout: 120000,
  });

  cy.get(selectors.CATEGORIES)
    .eq(2)
    // i use 'within', because i want to search **inside the selectors.CATEGORIES.eq(2) and not on the whole DOM**
    .within(() => {
      cy.get(dataCySelector("gridRow")).then(($optionsWrapper) => {
        const parentEl = $optionsWrapper.parent();
        const isMenuOpen = parentEl.css("display");

        // if i dont add the wait(), it selects the 1st 'menu options' instead of the **3rd**
        cy.wait(3000);

        if (isMenuOpen === "none") {
          console.log("*MENU IS CLOSE I OPEN*");
          cy.contains("category").click(); // OPEN THE MENU
          cy.contains("Front End").should("be.visible").click(); // click on the 'front end'
        } else {
          console.log("*MENU IS OPEN I DONT CLICK ON IT*");
          cy.contains("Front End").should("be.visible").click(); // JUST click on the 'front end'
        }

        cy.url().then(() => {
          cy.urlIncludes("/path/to/menu/option");
          cy.wait(3000);
          cy.contains(dataCySelector("AN_ELEMENT"));
        });
      });
    });
});

所以我的流程如下:


  1. 访问我想要的页面
  2. 获取
    CATEGORIES
    选择器(左侧导航栏上有5个菜单)
  3. 获得第三名
  4. 使用
    within
    深入了解它的孩子(我替换了
    then
    因为它搜索了整个 DOM)!!
  5. 我得到'gridRow'的父级并查看是否
    display=none
  6. !如果我不添加
    wait(3000)
    parentEl
    是第一个菜单包装器!!
  7. 比对后点击'选项链接'
  8. 用户被重定向到新页面,但我再次需要
    wait()
    来检查元素选择器是否存在。

这里一定有问题,我可以摆脱

wait
吗? 谢谢。

回答如下:

对于第二个

wait()
,如果您的问题与您的页面需要比默认超时更多的时间来加载这一事实有关,您仍然可以覆盖它。

  cy.url().then(() => {
    cy.url().should("contain", "/path/to/menu/option");
    cy.contains(dataCySelector("AN_ELEMENT"), {timeout: 30_000});
  });

对于第一个

wait
,If/Else 很奇怪。应该知道它何时打开,所以我会避免它(通过为这两种情况创建例如 2 个函数)然后,对于每种情况,我会在必要的地方添加一个
{timeout: 30_000}

发布评论

评论列表(0)

  1. 暂无评论