While 循环元素状态 cypress [英] While loop element state cypress

查看:45
本文介绍了While 循环元素状态 cypress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我想点击一个按钮直到它消失,但次数可能会有所不同,所以我想检查可见性状态,当可见 = 真点击按钮时,当可见 = 假结束测试但问题是我不知道如何将所有的链从 get 元素循环到最后.它单击一次按钮并因中断而停止;如果我删除中断它甚至不会永远单击它循环,主要问题是它第一次通过链时该值是真的但它不会重申

i have a issue, i would like to click on a button until it disappears but the number of times may vary so i would like to check the visibility state and while visible = true click button, when visible = false end test but the issue is that i don't know how to loop all of the chain from get element to the end. It clicks the button once and stops due to the break; if i remove the break it does not even click it loops forever, the main issue is that the first time it goes through the chain the value is true but it does not reiterate

cy.get('[idElem]')
      .then($isVisible => {
        return $isVisible.is(':visible');
      })
      .then(value => {
        while (value === true) {
          cy.get('[idElem]').click();
          break;
        }
      });

推荐答案

由于 cypress 的异步性质,您不能在 cypress 中使用 while/for 循环.在再次开始循环之前,赛普拉斯不会等待循环中的所有内容完成.但是,您可以改为执行递归函数,并在再次访问方法/函数之前等待所有内容完成.

You can't use while/for loops with cypress because of the async nature of cypress. Cypress doesn't wait for everything to complete in the loop before starting the loop again. You can however do recursive functions instead and that waits for everything to complete before it hits the method/function again.

所以你可以做这样的事情,它会起作用:

So you can do something like this instead and it'll work:

clickVisibleButton = () => {
        cy.get( 'body' ).then( $mainContainer => {
            const isVisible = $mainContainer.find( '#idOfElement' ).is( ':visible' );
            if ( isVisible ) {
                cy.get( '#idOfElement' ).click();
                this.clickVisibleButton();
            }
        } );
    }

然后显然在您的测试中调用 this.clickVisibleButton().我正在使用打字稿,并且此方法是在类中设置的,但您也可以将其作为常规函数来执行.

Then obviously call the this.clickVisibleButton() in your test. I'm using typescript and this method is setup in a class, but you could do this as a regular function as well.

这篇关于While 循环元素状态 cypress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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