Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select element with class name that starts with using Cypress

Tags:

cypress

I have some classes which are dynamically generated in React. They always have the same prefix but they all end differently

How can I use Cypress to select a class name that begins with X?

<div class="this-is-always-the-same-abcd"></>
<div class="this-is-always-the-same-efgh"></>
<div class="this-is-always-the-same-ijkl"></>
like image 950
Adrian E Avatar asked Nov 04 '19 19:11

Adrian E


People also ask

How do you identify an element with a class in Cypress?

To select an element by class you need to use . prefix and to select an element by its it, you should prefix id with # . The most common attribute you might find on your page would be a placeholder for an input or even a test-id where your selector starts and ends with square brackets.

How do you get the element by name in Cypress?

Get Element By Containing Text in Cypress You can simply use the contains() function along with the tag name and should be able to get the element.

How do you select an element with the class name?

class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.


2 Answers

To everyone who really need to target class and cannot (Or do not want) use data- attributes for some reasons. Solution is to use standard css selector.

cy.get('*[class^="this-is-always-the-same"]')

This will get all elements that has class starting with this-is-always-the-same.

like image 58
SergeS Avatar answered Sep 29 '22 05:09

SergeS


According to their Best Practices Documentation, you should use data-* attributes to provide context to your selectors and insulate them from CSS or JS changes.

It's suggested that you follow these guidelines:

  • Don’t target elements based on CSS attributes such as: id, class, tag.
  • Don’t target elements that may change their textContent.
  • Add data-* attributes to make it easier to target elements.

Instead, you should add a data-cy attribute to target the selector that you're testing.

You can use this playground to determine an unique selector.

like image 24
Manuel Abascal Avatar answered Sep 29 '22 06:09

Manuel Abascal