Skip to content Skip to sidebar Skip to footer

While Loop Element State Cypress

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

Solution 1:

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.


Post a Comment for "While Loop Element State Cypress"