How to get multiple elements with data-cy attributes

Viewed 634

I have a table with all cells marked with the data-cy attribute as so: [data-cy="cell-${row}-${column}].

Individually I have no trouble to get each cell with the classic cy.get, for example cy.get("[data-cy=cell-2-17]").click(), but I try to test the click on multiple cells holding the control key but I couldn't achieve that.

In this answer it says to simply concat the selectors passed to cy.get but it didn't work for me, I tried with and without the " around the data-cy names:

cy.get('[data-cy="cell-2-17"][data-cy="cell-4-10"]').click({multiple: true, ctrlKey: true})`

Could you tell me how to get multiple elements using the data-cy attribute?

1 Answers

If you concatenate selectors (without space or + between), it means the element must have all those selectors.

There's not really a concise way to provide a list of required attributes.

Two things that help are wildcards and filters

const cellsWanted = ['cell-2-17', 'cell-4-10']

cy.get('[data-cy^="cell-"]')   // wildcard anything that starts with "cell-"
  .filter((index, el) => cellsWanted.some(cell => el.getAttribute('data-cy') === cell))
  .click({multiple: true, ctrlKey: true})`

Multiple selectors with comma between

Just found an easier way using jquery multiple selectors

cy.get('[data-cy="cell-2-17"], [data-cy="cell-4-10"]')
  .should('have.length', 2)
  .click({multiple: true, ctrlKey: true})
Related