While loop element state cypress

Viewed 1454

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;
        }
      });
1 Answers

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();
            }
        } );
    }

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.

Related