Skip to content
Advertisement

Cypress click on set of elements but not loop forever

I have a few places that I need to click on a number of elements but I don’t want it to loop through. I feel that the answer is right in front of me, but cant find the right solution.

Here is one code example which right now is stuck in a forever loop:

for(let n = 1; n <= 19; n++){
        cy.get('li.active > .nav > :nth-child(n) > a').click({multiple: true})
        cy.wait(400)
    }

I have 19 elements all of which are the same just numbered 1-19 and I just want the test to click on them, wait to let it show the page, then click the next one.


Answer

            cy.get('#side-menu > :nth-child(2) > a').click()
        cy.wait(400)
        cy.get('li.active > .nav').each(($ele) => {
  cy.wrap($ele).find('a').click({multiple:true})
})

Also took care of my other for loop that went on for forever and never stopped unless manually stopped like this original issue by replacing it with each() as well.

    cy.get('#side-menu > li > a').each(($ele) => {
        cy.wrap($ele).click({multiple:true})
        })
    ```

Advertisement

Answer

You can use the each() loop to iterate through your elements and click on the buttons one by one –

cy.get('li.active > .nav').each(($ele) = > {
  cy.wrap($ele).find('a').click()
})
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement