I am using dynamic class names in my react app, they are generated by the CSS modules.
The className={styles.myclass}
is compiled into class="Myclass__1234"
so the cypress cy.get(.'myclass')
will not work.
As an example:
import styles from 'styles/About.module.css';
const About = () => {
return (
<div className={styles.about}>
<h1 className={styles.title}>About Me Page</h1>
</div>
);
};
export default About;
To do a check on the title text you would need to do this:
cy.get('About_title__1234').should('not.be.empty');
This means I have to dive into the dev tools to find the real class name every time.
Is there any other method I could use?
I suppose cy.get('h1')
would work, but I may want multiple h1 tags on the page later on.
Some ideas for the example code shown:
Specify the text
cy.contains('h1', 'About Me Page')
is logically equivalent to cy.get('.About_title__1234').should('not.be.empty')
because it searches for specific text.
You don't have to add an explicit .should()
assertion every time, the query has built-in assertions as well.
Use partial class attribute selectors
You probably know the class has About
(from component name) and title
(semantically named in css) so you could use ^=
in the selector to indicate just the start of the class should be matched - cy.get('[class^="About_title"]').should('not.be.empty')
Traversal of the DOM
Instead of thinking about attributes of the target element is isolation, use it's relationship to known easily selected elements to navigate the DOM tree, see Examples of traversing DOM elements in Cypress
Example:
cy.get('main')
.find('h1')
.first()
.should('not.be.empty')
More generally, Cypress prefers data-
attributes, see Selecting Elements
Best Practice: Use data-* attributes to provide context to your selectors and isolate them from CSS or JS changes.
The Testing Library top pick is role based selectors, see Priority.
Based on the Guiding Principles, your test should resemble how users interact with your code (component, page, etc.) as much as possible. With this in mind, we recommend this order of priority:
getByRole
: This can be used to query every element that is exposed in the accessibility tree.
This makes sense if you are adding accessibility attributes to your code (some say every web page should be coded this way).