代码之家  ›  专栏  ›  技术社区  ›  Rubén Campos Sosa

如何在Cypress中停止“for”循环?

  •  0
  • Rubén Campos Sosa  · 技术社区  · 2 年前

    这是我正在使用的代码:

    it('Test to stop a FOR loop', function () {
      cy.visit('https://docs.cypress.io/guides/overview/why-cypress');
      
      for (let i = 0; i < 5; i++) {
        cy.wait(1000);
        cy.url().then((url) => {
          cy.log(`**${url}**`);
          if (url.includes('api')) {
            break;  // This fails
          }
          if (url.includes('overview')) {
            cy.log('**The URL includes OVERVIEW**');
            cy.get('[href="/api/table-of-contents"]').click();
          };
          if (url.includes('plugins')) {
            cy.log('**The URL includes PLUGINS**');
            cy.get('.navbar__inner > :nth-child(1) > :nth-child(3)').click();
          };
        });
      };
    });
    

    我想遍历几个页面,并在脚本遇到特定URL时停止。我尝试过使用 return 而不是 break ,但这不起作用。有什么想法吗?

    我尝试过:

    if (url.includes('api')) {
      return;
    };
    

    但它看起来并没有退出 for

    2 回复  |  直到 2 年前
        1
  •  1
  •   Maxwell    2 年前

    但你到底想测试什么?您只调用过cy.visit()一次,并提供了一个URL,因此无法以这种方式遍历多个页面。Cypress的目标是创建断言,将两件事放在一起进行比较,并评估它们是否失败或通过。

        2
  •  0
  •   Adrid    2 年前

    我认为 return 语句不会退出循环或函数,因为它的行为与同步JavaScript不同。

    我在下面添加代码。

    it("Test to stop a FOR loop", function () {
      cy.visit("https://docs.cypress.io/guides/overview/why-cypress");
    
      function iterate(i) {
        if (i < 5) {
          cy.wait(1000);
          cy.url().then((url) => {
            cy.log(`**${url}**`);
            if (url.includes("api")) {
              // Stop the recursion
              return;
            }
            if (url.includes("overview")) {
              cy.log("**The URL includes OVERVIEW**");
              cy.get('[href="/api/table-of-contents"]')
                .click()
                .then(() => {
                  iterate(i + 1); // Continue with the next iteration
                });
            } else if (url.includes("plugins")) {
              cy.log("**The URL includes PLUGINS**");
              cy.get(".navbar__inner > :nth-child(1) > :nth-child(3)")
                .click()
                .then(() => {
                  iterate(i + 1); // Continue with the next iteration
                });
            } else {
              iterate(i + 1); // Continue with the next iteration
            }
          });
        }
      }
    
      iterate(0); // Start the recursion with the initial index
    });
    
    
    

    在此代码中 iterate 函数是为每次迭代递归调用的。

    这样可以确保每次迭代都等待异步Cypress命令完成,然后再进行下一次迭代。

    当满足所需条件时,递归将停止 (url.includes('api')) 满足。