Mastodon hachyterm.io

A few days ago, I updated a React application that uses Jest and Enzyme for testing.

The new tests yielded errors like cannot find module 'react-test-renderer'.

Solution: Install react-test-renderer and enzyme-to-json as dev dependencies, and re-factor tests to use enzyme-to-json.

npm i --save-dev react-test-renderer enzyme-to-json

In your package.json file, add the serializer to your jest config:

{
 "jest": {
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  }
}

Example test file before update:

import React from 'react'
import { shallow } from 'enzyme'
import renderer from 'react-test-renderer'

import About from '../About'

test('About renders a snapshot properly', () => {
  const tree = renderer.create(<About />).toJSON()
  expect(tree).toMatchSnapshot()
})

After re-factor:

import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'

import About from '../About'

test('About renders a snapshot properly', () => {
  const tree = shallow(<About />)
  expect(toJson(tree)).toMatchSnapshot()
})