How cy.click on all buttons starting from 2nd element in Cypress?
Asked Answered
E

3

5

How can I click on all the the buttons but starting from the 2nd element? Here is my code:

it('Click menu buttons one by one', function () {

    cy.visit('http://localhost:25000/', { timeout: 300000 })
    cy.wait(10000)
    cy.get('.dijitReset.dijitInline.dijitMenuItemLabel.dijitMenuItem', { timeout: 200000}) .click({multiple: true }) 
    cy.waitSomeTime(10000)

})
Ecchymosis answered 11/1, 2021 at 13:55 Comment(1)
Can you share a screenshot of your html DOM, then I would be able to help you with exact code. if not, you can use each() or eq() to achieve this.Hew
K
6

Use each():

cy
  .get('.dijitReset.dijitInline.dijitMenuItemLabel.dijitMenuItem')
  .each(($btn, index) => {
    if (index >= 1) cy.wrap($btn).click();
});

More examples could be found in the doc here.

Kirkpatrick answered 11/1, 2021 at 15:49 Comment(2)
This approach is briliant. I would have used .then() and a for loop.Egwan
Not so much - the .click() action will often refresh the list and invalidate the cy.get() query list.Incommensurable
I
7

If you use .each() as suggested in the accepted answer, the .click() action can cause the DOM to refresh and result in a "detached from DOM" error.

A better way is to use the index to get a clean query for each iteration,

const selector = '.dijitReset.dijitInline.dijitMenuItemLabel.dijitMenuItem'

cy.get(selector)
  .each((_, index) => {
    if (index >= 1) {
      cy.get(selector).eq(index).click()
    }
  })
Incommensurable answered 3/9 at 21:10 Comment(0)
K
6

Use each():

cy
  .get('.dijitReset.dijitInline.dijitMenuItemLabel.dijitMenuItem')
  .each(($btn, index) => {
    if (index >= 1) cy.wrap($btn).click();
});

More examples could be found in the doc here.

Kirkpatrick answered 11/1, 2021 at 15:49 Comment(2)
This approach is briliant. I would have used .then() and a for loop.Egwan
Not so much - the .click() action will often refresh the list and invalidate the cy.get() query list.Incommensurable
M
4

Something new I saw today in a Cypress internal test

cy.get('.dijitReset.dijitInline.dijitMenuItemLabel.dijitMenuItem')
  .invoke('slice', 1)  // take from 2nd onwards
  .click({multiple: true})

Ref: jQuery .slice()

Reduce the set of matched elements to a subset specified by a range of indices

Melanoid answered 14/10, 2021 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.