Lisandro Pastinante
Lisandro Pastinante

Reputation: 51

Configure enzyme-to-json with Jest

I'm trying to test my react components with jest and Enzyme.

When I import enzyme-to-json in the particular test case it works. But instead of doing it manually I would like to configure jest to do it.

I already tryed adding "snapshotSerializers": ["enzyme-to-json/serializer"] to my jest config but it doesn't seem to be working.

How do I configure jest to use enzyme-to-json on my wrappers?

This code works

Header.test.js

import React from 'react'
import { shallow } from 'enzyme'
import toJSON from 'enzyme-to-json'
import Header from '../../components/Header'

test('Should render Header correctly', () => {
    const wrapper = shallow(<Header />)
    expect(toJSON(wrapper)).toMatchSnapshot()
})

I want Jest to automatically use enzyme-to-json in all my wrappers so that this code works aswell:

Header.test.js

import React from 'react'
import { shallow } from 'enzyme'
import Header from '../../components/Header'

test('Should render Header correctly', () => {
    const wrapper = shallow(<Header />)
    expect(wrapper).toMatchSnapshot()
})

jest.config.json

{
    "setupFiles": [
        "raf/polyfill",
        "<rootDir>/src/tests/setupTests.js",
    ],
    "snapshotSerializers": ["enzyme-to-json/serializer"]
}

Test script

"test": "jest --config=jest.config.json"

expected

exports[`Should render Header correctly 1`] = `
<header>
  <h1>
    Title
  </h1>
  <NavLink
    activeClassName="is-active"
    exact={true}
    to="/"
  >
    Home
  </NavLink>
  <NavLink
    activeClassName="is-active"
    to="/create"
  >
    Create
  </NavLink>
</header>
`;

result

exports[`Should render Header correctly 1`] = `ShallowWrapper {}`;

Upvotes: 1

Views: 6814

Answers (3)

Urrri
Urrri

Reputation: 11

I had problem with jest config. Following entry was just ignored:

"snapshotSerializers": ["enzyme-to-json/serializer"]

So I found manual replacement of that config. In the file setupTests add following:

import serializer from "enzyme-to-json/serializer";
expect.addSnapshotSerializer(serializer);

file setupTests can be added to the config (if not auto-defined as in CRA) like following:

setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"]

Upvotes: 0

EHorodyski
EHorodyski

Reputation: 794

I'm having the same issue. Funny thing is, I copied your file and my setupTests is at the root of the src folder and Jest still ran happy (no Adapter complaints!).

For now I'm just using the import.

Upvotes: 0

Lisandro Pastinante
Lisandro Pastinante

Reputation: 51

There was an extra "," on my jest config file but somehow the console was not able to detect the error.

jest.config.json

{
    "setupFiles": [
        "raf/polyfill",
        "<rootDir>/src/tests/setupTests.js", <------- this comma
    ],
    "snapshotSerializers": ["enzyme-to-json/serializer"]
}

Remove the comma to fix

Upvotes: 3

Related Questions