angularcypress

Cypress use regex to retrieve elements with matching text in id


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();
    });
  });

Solution

  • 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.