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})
})
```
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()
})
If your page refreshes each click, you cannot use Cypress .each() because you will get "detached from DOM" error.
Try a recursive function
it('tests the nav buttons', () => {
function clickNav(buttonNum) {
if (buttonNum === 20) return // finished
cy.get('li.active > .nav > :nth-child(n) > a').click()
cy.wait(400)
clickNav(++buttonNum) // next
}
clickNav(1)
})
But something else is going on, technically your loop should also work.
thanks for the solutions - Alpan's worked as such:
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})
})
Forgot I had to open the drop down via the nth-child click then added the {multiple:true} inside of click in the each()