在赛普拉斯中使用if/else从while循环退出 [英] Exit from while loop with if/else in Cypress

查看:50
本文介绍了在赛普拉斯中使用if/else从while循环退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个测试案例,要求我重新加载页面 N 次,并比较其标题以获取一个值,如果该值不存在,则中断while循环而不会出现错误

I am writing a test case which requires me to reload the page N number of times, and compare its title for a value, if that value does not exists then break the while loop without rising error.

下面是一个演示程序,类似于我要实现的演示程序.

Below is a demo program, similar to the one that I am looking to implement.

/// <reference types='cypress' />

it("Visiting Google",function(){
    var webUrl = 'https://html5test.com/'
    cy.visit(webUrl)
    var loop_iter = 0
    while(loop_iter < 5)
    {
        cy.get('body:nth-child(2) div:nth-child(2) div.header h1:nth-child(1) > em:nth-child(2)').then(($text_data) =>{
            if($text_data.text().contains('HTML123'))
            {
                cy.log(" --> ITERATION = ",loop_iter)
                cy.reload()
            }
            else
            {
                cy.log("Unknown website")
                loop_iter = 10
            }
        })
        loop_iter += 1
    }
})

我需要一种在执行else部分时从while循环中中断的方法,而不会引起任何错误.

I need a way to break from the while loop when the else part is executed, without rising any error.

当false时的if条件返回AssertionError,在这种情况下,它应该执行else部分.

The if condition when false returns AssertionError, in such case it should execute else part.

推荐答案

请查看示例食谱

Please take a look at the sample recipe Page reloads. It uses recursion as suggested in comments.

这是您适应该模式的代码,

This is your code adapted to the pattern,

it('reload until "HTML" disappears', () => {

  // our utility function
  const checkAndReload = (recurse_level = 0) => {

    cy.title().then(title => {
      if (title.includes('HTML') && recurse_level < 5) {

        cy.log(" --> ITERATION = ", recurse_level)
        cy.wait(500, { log: false })           // just breathe here
        cy.reload()                            // reload
        checkAndReload(recurse_level + 1)      // check again

      } else {
        cy.log("Unknown website") 
      }
    })
  }

  cy.visit('https://html5test.com/')      // start the test by visiting the page
  checkAndReload()                        // and kicking off the first check
})

这篇关于在赛普拉斯中使用if/else从while循环退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆