Tips for testing React applications with Cypress

I noticed my React components get translated into DOM elements with their name in the class attribute. I have used this in Cypress to get the elements without using `data-` attributes.

I have a Card component created using styled-components that gets translated into a div like this

<div class="Card_card__H374l">...</div>

The beginning of the class attribute value is predictable, however the second is randomly assigned by React in order to keep track of it. So to locate the Card component in cypress I can use

cy.get('*[class^="Card"]')

The CSS selector allows you to keep the test readable without having to add many data- attributes to your application JSX

References:

https://stackoverflow.com/a/59849612/1731531

Leave a comment