5

I have multiple div elements with the id features-##### and features-#####, where the # is a dynamic figure.

How would I get Cypress to find all elements with the matching part of the id features-, and then click on the first or second in a programmatic manner?

This is that I have done so far, but I can't figure out hwo to use regex to retrieve all the elements I did then process them programmatically.

  describe('builder features component', () => {
    it('should allow the user to select a features component', () => {
      cy.get(el).should('div.id', /^features-\w+/).first().click();
    });
  });
methuselah
  • 12,766
  • 47
  • 165
  • 315

3 Answers3

12

Rich Churcher is right, the approach he mentioned should be your first choice. But in the event that you don't have control over the app and you cannot add data-cy attributes, you may use css selector syntax to achieve this.

const featuresSelector = '[id^="features-"]'; 

This will select any element with an id that starts with... See a good explanation at How to select all elements whose ID starts and ends with specific strings?

And then you may use this selector like this:

cy.get(featuresSelector).first().click(); // click the 1st element in the collection
cy.get(featuresSelector).eq(1).click(); // click the second element (index starts at 0)
cy.get(featuresSelector).eq(-1).click(); // click the last element
cy.get(featuresSelector).each((element, index, collection) => {
    // or event loop through the entire collection
})
PeaceAndQuiet
  • 1,692
  • 8
  • 13
8

Cypress suggests using data- attributes to select elements. If you add data-cy="builder-feature" to all your features, for example, you won't have to care about regular expressions which will just slow your tests down.

cy.get('[data-cy="builder-feature"]').first().click()

See Best Practices.

Rich Churcher
  • 7,361
  • 3
  • 37
  • 60
2

Uses the contains() function. The function can receive regex as a parameter

cy.contains(/^features-\w+/).click();
Chris
  • 2,117
  • 13
  • 18