SixtyEight
SixtyEight

Reputation: 2490

How should I setup the Enzyme Adapter config file with Jest?

I've followed the instructions in other projects and threads but can't make React find the Enzyme config file.

package.json

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
"jest": {
    "collectCoverageFrom": [
      "src/**/*.{js, jsx, mjs}"
    ],
    "setupFiles": [
      "<rootDir>src/setupTests.js"
    ]
  }

src/setupTests.js

import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
export { shallow, render, mount } from "enzyme";
export { shallowToJson } from "enzyme-to-json";

Enzyme.configure({ adapter: new Adapter() });

export default Enzyme;

the error when running tests

Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.
To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`
before using any of Enzyme's top level APIs, where `Adapter` is the adapter
corresponding to the library currently being tested. For example:

import Adapter from 'enzyme-adapter-react-15';

Any help would be much appreciated. Thanks

Upvotes: 1

Views: 3252

Answers (2)

AATHIL TA
AATHIL TA

Reputation: 1

Add setupFilesAfterEnv: ['<rootDir>src/setupTests.js'] in jest.config.js and it will work fine

Upvotes: 0

Lidor Avitan
Lidor Avitan

Reputation: 1404

Follow by this configuraion:

// test-setup.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

then add a setupFilesAfterEnv key in your jest configuration and point to that file. For example, if your jest configuration is in package.json:

// package.json
{
  "jest": {
    "setupFilesAfterEnv": ["<rootDir>src/setupTests.js"]
  }
}

from the enzyme docs: https://airbnb.io/enzyme/docs/guides/jest.html

A list of paths to modules that run some code to configure or set up the testing framework before each test. Since setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment.

Upvotes: 5

Related Questions