I have 15 buttons on a page. I need to test each button.
I tried a simple for loop, like
for (var i = 1; i < 15; i++) { cy.get("[=buttonid=" + i + "]").click() }
But Cypress didn't like this. How would I write for loops in Cypress?
To force an arbitrary loop, I create an array with the indices I want, and then call cy.wrap
var genArr = Array.from({length:250},(v,k)=>k+1) cy.wrap(genArr).each((index) => { cy.get("#button-" + index).click() })
While cy.wrap().each()
will work (one of the answers given for this question), I wanted to give an alternate way that worked for me. cy.wrap().each()
will work, but regular while/for loops will not work 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.
Here is a simple example to explain this. You could check to see if a button is visible, if it is visible you click it, then check again to see if it is still visible, and if it is visible you click it again, but if it isn't visible it won't click it. This will repeat, the button will continue to be clicked until the button is no longer visible. Basically the method/function is called over and over until the conditional is no longer met, which accomplishes the same thing as a for/while loop, but actually works with cypress.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With