Working with Dynamic Element Ids, Classes and Attributes— Cypress

<div id="ProductGrid-gVjGQiI">
<div id="ProductGrid-MenYuRd">

Using Regex

We find elements by supplying a string that represents an element in most test automation frameworks, the same goes for Cypress. We run cy.get(“#someBox”) to get an element which has an ID of “someBox”. Because we supply strings, we can leverage Regular Expressions (Regex) to find us a specified string that matches a specific pattern. The most common Expressions I use are:

  • ^ to indicate that a string must start with the specified string
  • * to indicate that a string must contain the specified string
<div class="MuiButtonBase-root MuiListItem-root jss457 MuiListItem-gutters MuiListItem-divider MuiListItem-button" tabindex="0" role="button" aria-disabled="false" data-testid="list-item-elkjhk">
cy.get(‘[data-testid^=”list-item-”]’)
cy.get(‘[data-testid^=”list-item-”]’).eq(3)
<div class="MuiButtonBase-root MuiListItem-root jss457 MuiListItem-gutters MuiListItem-divider MuiListItem-button" tabindex="0" role="button" aria-disabled="false" data-testid="elkjhk-static-stuff-pgyt">
cy.get(‘[data-testid*=”-static-stuff-”]’)

Reusability

Finally, we could build on-top of this approach to find elements by reusing it as a custom command:

  • A custom command that accepts a parameter to populate the value part of the data-testid
  • Once you import & bind the custom command, you can then call it in the test spec
  • We need to make sure that the = part stays in the test, because we need this to place a * or ^ Expression before the equals for the pattern to work and the custom command to remain reusable
  • You should then be able to chain a .eq(), .click(), .type() or .then(()=>) on the custom command in the test if you need to process the element further

Conclusion

A simple but effective way to work with web-elements that have dynamic values. You could use other Regular Expressions of course which may suit your needs better and this should work for any element Attribute, not only data-testids.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store