Cypress and React

Apply Cypress testing to the rest of our Stimulus and React pages in this lesson.

The problem with styled-components

We don’t need to do anything, in general, to test React, since the Cypress tests aren’t concerned with the underlying framework. We do, however, have a specific problem related to the React tools in our code. That problem is our styled-components.

Styled-components, which we added to our React code in Introduction to CSS, are useful, but they also work by adding a dynamic, random class name to the component. Dynamic, random class names are not easy to find in a test or make assertions about.

There doesn’t seem to be a way to manage this on the styled-components side. We could imagine a test setting for styled-components where the class names were discoverable, but that doesn’t exist yet.

Solution

The easiest way to get attributes that our tests can find is to add them ourselves, so we add a couple of new attributes to the ButtonSquare component inside the Seat component. If we are concerned about performance, we can make use of these attributes while not in production, but it won’t be a noticeable issue in this case:

Get hands-on with 1200+ tech skills courses.