Judik Dávid
June 6, 2017
#Web #iOS #node.js #Mac #Wim

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.

Make sure you have a .babelrc

After writing my tests, the first error I’ve got was this:

- SyntaxError: /Users/judikdavid/repos/jest-snapshot/src/__tests__/App.test.js: Unexpected token (9:6)
               7 |   it('default', () => {
               8 |     const component = renderer.create(
          >  9 |       <App/>
                  |       ^
            10 |     );

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:

  "presets": ["es2015", "es2016", "react"],
 "plugins": [

Requiring CSS files in React Components

The next error I got was:

- SyntaxError: Unexpected token ILLEGAL
               at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:306:10)

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:

var babelJest = require(‘babel-jest’)
module.exports = {
process: function(src, filename) {
  if (/\.css$/.test(filename)) {
      return ‘’
  } else {
    return babelJest.process(src, filename)

Hint: make sure to use:

$ jest --no-cache

after adding your preprocessor.

React-dom issue with react-test-renderer

And the last error was this:

- Invariant Violation: ReactCompositeComponent: injectEnvironment() can only be called once.
       at invariant (node_modules/fbjs/lib/invariant.js:38:15)

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:

New issue Invariant Violation: ReactCompositeComponent: injectEnvironment() can only be called once..

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 :)