Ad

How Should I Setup The Enzyme Adapter Config File With Jest?

- 1 answer

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

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad