Testing CSS-in-JS
Popular CSS-in-JS libraries like styled-components or emotion can also be tested with the help of jest-styled-components or jest-emotion respectively. These packages improve Jest’s built-in snapshot testing experience and are a great way to help avoid unintended changes to your website’s UI. Please refer to your package’s documentation to see if it also offers testing capabilities.
Snapshot serializers like jest-styled-components
or jest-emotion
modify the standard output to a more meaningful and readable snapshot, e.g. by removing unnecessary information or displaying data in another format. Which ultimately leads to more comparable and effective snapshot tests.
By default snapshots of your styled components show the generated class names (which you didn’t set) and no styling information. When changing the styles you’ll only see the diff of some cryptic class names (hashes). That’s why you should use the above mentioned snapshot serializers. They remove the hashes and format the CSS in style elements.
For this example you’ll use emotion. The testing utilities of emotion and glamor are largely based on jest-styled-components so they have a similar usage. Please have a look at the testing section of your library to follow along.
Installation
As Gatsby’s emotion plugin is using babel-plugin-emotion
under the hood you’ll also need to install it so that Jest can use it.
If you followed along with the Unit testing guide you’ll have the file jest-preprocess.js
at the root of your project. Open that file and add the plugin:
In order to tell Jest to use the serializer you’ll need to create the file setup-test-env.js
which will be run automatically before every test. Create the file setup-test-env.js
at the root of your project. Insert this code into it:
Lastly you need to tell Jest where to find this file. Open your package.json
and add this entry to your "jest"
section:
Usage
In this example you’ll use react-test-renderer
but you can also use @testing-library/react or any other appropriate library. Because you created the setup-test-env.js
file you can write your unit tests like you used to do. But now you’ll also get the styling information!
The resulting snapshot will look like this:
If your styled component depends on theme
via ThemeProvider
you’ll have two options:
- Wrap all your components with the
ThemeProvider
- Use API helpers (have a look at the library’s documentation, e.g. styled-components or emotion)
And this is where snapshots tests really shine. If you change, e.g. the primary color in your theme file you’ll see which components get affected by this change. This way you can catch unintended changes to the style of your components.
This example uses the first option:
The resulting snapshot will look like this:
Edit this page on GitHub