Unit Testing Styled Components
Unit testing React components isn’t always easy. In this short article i’ll show some tricks to make our lives a little easier using Enzyme.
In a project I’m working on, we are testing each level of the components hierarchy with shallow rendering and snapshot testing. That way if something brakes in a low level component, the tests that rely on this component won’t fail and you’ll quickly be able to pinpoint the problem.
We are striving to get to high coverage so if we have most of the system covered with shallow rendered components you’ll easily see any changes that have effects you weren’t expecting.
In this testing strategy, you’ll probably want to see the DOM the component produces, including the CSS, so Jest could shout at any changes in these aspects. Let’s try to produce a simple snapshot test using Styled Components for example.
For this simple styled component:
And with this simple test:
We’ll get this super weird snapshot:
If you look closely you could see a representation of the css. But that won’t do.. There is a lot of noise and it would be hard to understand what actually changed. Also, it won’t catch interpolated values, which makes it impossible to test the styled component in different situations.
Enzyme’s dive to the rescue!
A solution to this problem is using enzyme’s dive() function. This gives us an option to look behind the layers of objects that styled components (or any other tool for that matter) is wrapping our components with.
Let’s try to dive():
This is even worse! It’s some general wrapper with no css whatsoever. Not really what we’d expect to see. But don’t worry, darkness always comes before the light, so let’s try to dive once more:
Well, it’s the same. Not there yet. Another dive!
Finally! we found our div element, but no CSS :(
To overcome this and see the actual CSS we can use jest-styled-components that will turn the above snapshot into this lovely thing:
This describes everything we wanted to know about the component’s rendering — the fact it’s a div and the actual CSS.
The amount of diving we have to do varies between projects and even between components. There are styled components that wrap other styled components or other regular components. To minimize code duplication and maintenance we created a custom render function that dives recursively until it reaches a basic element. The code looks something like this:
We’ve found this formula works for all our styled components across the projects, even when using third-party component libraries.
Hope you can find it useful!