Working with Dynamic Element Ids, Classes and Attributes— Cypress

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

Using Regex

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

  • 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

Software Developer in Test

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

React Native & Typescript | Imports & Exports

How to Create a Simple Movie App with Vanilla JavaScript

Web Development… How to get started in 2017?

How to use jQuery with React the right way

Introduction to React Native

JavaScript closure in plain language and one practical real-world example

JavaScript Closures in Plain Language

What is the Document Object Model(DOM)?

JavaScript Data Structures and Algorithms (Search Algorithms, Part 2)

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
Ahmed Alsaab

Ahmed Alsaab

Software Developer in Test

More from Medium

How to Install Java and set the JAVA_HOME in macOS with zshell

Testing with Jest

How To Install & Create Your First Test With Cypress.io

Getting Started with awesome Cypress Automation Framework