First impressions using Jest and snapshot testing with React
I was keen to try out snapshot testing after seeing it in action in this Facebook video:
It seemed easy, you just add Jest to your project, using at least React 15.3 with it.
First I tried to test simple preexisting form elements that we had put together at our company. Looking back this was a good choice, because this way I found a couple of issues when integrating Jest to an existing project.
After writing my tests, the first error I’ve got was this:
I was sure that this had something to do with Babel not compiling right, so I checked it and since then I’ve used create-react-app. I had no .babelrc file, so I had to create one with the following:
The next error I got was:
After a couple of minutes I figured out that it had something to do with using CSS Modules and Jest not being able to interpret them.
You can fix this issue by adding a preprocessor to Jest, something like this:
Hint: make sure to use:
after adding your preprocessor.
And the last error was this:
Now I had no idea what was happening but was able to limit the error to one of my components, which was something. After I googled the error, I found this thread:
As it turned out, if you use react-dom in one of your components or dependencies, that causes a problem with react-test-renderer.
The solution was as Dan Abramov suggested it, add this to your tests:
Now I can run Jest with snapshot testing and it seems pretty cool. Looking back I could have prevented my first two errors if I was thinking beforehand, but the third was a though one :)