Search code examples
javascriptregexattributescypress

How can I use regex on an attribute value in cy.get()?


The application has list of items in a table and items have [id=item[0].setupCost, id=item[1].setupCost, id=item[2].setupCost] etc.

There's a functionality to add items also, so the index keeps on increasing.

I want to get input field regardless of using magic numbers. For eg (cy.get('[id=item[some_regex].setupCost]')


Solution

  • The regex that applies is \[id="item\[\d+\].setupCost\].

    Enclose the regex in forward slashes, not quotes.

    cy.get(/\[id="item\[\d+\].setupCost\]/)
    

    But don't use it

    This syntax is undocumented - it works (in Cypress v9.5.0) but it only returns one result.

    So if you want to count your items, this will fail

    cy.get(/\[id="item\[\d+\].setupCost\]/)
      .its('length')
      .should('eq', 3)   // ❌
    

    Partial attribute selector

    If you want to use partial attribute selectors, this is strongest as it includes .setupCost

    Ref Find the element with id that starts with "local-" and ends with "-remote"

    cy.get('[id^="item"][id$=".setupCost"]')  // use "starts-with" and "ends-with" selectors
    

    This succeeds with the count test

    cy.get('[id^="item"][id$=".setupCost"]')
      .its('length')
      .should('eq', 3)   // ✅