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

Web Scraping with Java and Jsoup

React Native Lists: Load More by Scrolling

Solid Design Principles In Javascript (Part 2) — Open-Closed Principle

Introduction to JavaScript Data Structures and Algorithms — array

CS373 Spring 2021: Nathaniel Jackson

Fundamental React.js

K-pop Star Season 6 (2016) (Ep 1–16) (Ongoing)

Hi, I am Object.defineProperty. I do exist.

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 setup Cypress 10.x.x with Cucumber and Typescript

Most used basic Cypress Commands — Part One

Assertions in Selenium WebDriver

Cypress SetUp Steps