85

I created a new React application by create-react-app and I wanted to write a unit test to a component named "MessageBox" that I created in the application. This is the unit test that I wrote:

import MessageBox from "../MessageBox";
import { shallow } from 'enzyme';
import React from 'react';

test('message box', () => {
   const app = {setState: jest.fn()};
   const wrapper = shallow(<MessageBox app={app}/>);
   wrapper.find('button').at(0).simulate('click');
   expect(app.setState).toHaveBeenLastCalledWith({modalIsOpen: false});
});

I also added a file under 'src' folder named 'setupTests.js' with the content:

import * as enzyme from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';

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

I ran it by:

npm test

and I got the error:

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() })

Do you know what can solve this problem?

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • 2
    The current error message as of the date of this comment also has a URL to the documentation. Visiting that URL mostly explains what to do. – Code-Apprentice May 16 '18 at 03:48
  • @CrazySynhax, please accept another answer from '@Mikel', cause it makes configuration shared and your tests will look more clear. Having such explicit configuration in each test is too verbose. – Alexandr Jun 22 '20 at 12:00

18 Answers18

94

Add it to your test case file.

import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { shallow, configure } from 'enzyme';

configure({adapter: new Adapter()});
test('message box', ()=> {
     ...
})
Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
GAJESH PANIGRAHI
  • 1,204
  • 10
  • 17
28

Also, if you don't want to import your setupTests.js file into every test file, you can place it in your package.json folder:

  "jest": {
     "setupTestFrameworkScriptFile": "./test/setupTests.js" }

Update:

Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.

https://jestjs.io/docs/en/configuration

Ali Ben Messaoud
  • 11,690
  • 8
  • 54
  • 87
  • 1
    For a useful answer this reaction needs to be extended. Explain why this is an answer to the question. – Jeroen Heier Oct 23 '18 at 14:52
  • 8
    for people using creat-react-app, you don't have to make entry in package.json file. just create setupTests.js under src and it will be automatically picked. Also just ust import Adapter not * as Adapter – Priyank Thakkar Nov 22 '18 at 21:17
  • Here is more info supporting Priyank's comment: https://github.com/airbnb/enzyme/issues/1265 Mikel gives an example src/setupTests.js file in another answer. – mojave Jan 02 '19 at 01:23
22

The file 'setupTests' has to be imported to the test file:

import MessageBox from "../MessageBox";
import { shallow } from 'enzyme';
import React from 'react';
import "../setupTests"

test('message box', ()=> {
     ...
})
CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • this is what fixed it for me. – Jim41Mavs Nov 03 '20 at 22:51
  • This was the only thing working for me as well, but I noticed it only was an issue in Jest Runner extension for VS Code, so I found some configurations for it. See [my post](https://stackoverflow.com/a/66340321/7584643). – Dennis Persson Feb 23 '21 at 20:13
16

As Priyank said, if you are using Create React App, it will pick up the configuration from src/setupTests.js.

Add:

import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

configure({ adapter: new Adapter() })
Mikel
  • 5,902
  • 5
  • 34
  • 49
  • why we need Adapter, like in the official docs also they are telling use the adapter but why it is needed. Beginner to jest and enzyme . I don't know whether its a good question or not – Learner Jan 19 '19 at 15:24
  • 1
    For my case insteady of naming the configuration file as "setupTests.js", I had named it as "setUpTests.js". when I changed the name it worked. – Ivan Feb 03 '19 at 20:53
  • 1
    This works. For Typescript projects it needs to have a .ts extension: src/setupTests.ts – gkri Nov 26 '19 at 13:59
10

A lot of answers are saying import setupTests.js into your test file. Or configure enzyme adapter in each test file. Which does solve the immediate problem.

But long term, if you add a jest.config.js file to the project root. You can configure it to run a setup file on launch.

jest.config.js

module.exports = {
  setupTestFrameworkScriptFile: "<rootDir>/src/setupTests.ts"
}

This tells Jest to run setupTest.ts every time it's launched.

This way if you need to add polyfills or add global mock like localstorage, you can add it to your setupTests file and its configured everywhere.

The Enzyme docs don't cover integration with Jest, so it is confusing to fuse these two together.

Lex
  • 4,749
  • 3
  • 45
  • 66
7

For me when using React with create-react-app I had to make sure the file name was correct. The file has to be src/setupTests.js with an s at the end of Tests.

Inside setupTests.js is the following:

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

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

When running npm run test it auto finds the setupTests.js file. There is no need to import it into each test file.

Daniel Butler
  • 3,239
  • 2
  • 24
  • 37
  • this works only when i put it inside `.test.js` file strangely not works when i put the same code in `setupTests.js` file added dependency `npm i enzyme-adapter-react-16 enzyme-to-json --save-dev` lets see – Ashish Kamble May 05 '21 at 12:14
3

You need to use the import like this:

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

This way: (import * as Adapter from ...) returns a message "TypeError: Adapter is not a constructor."

Filipe
  • 111
  • 1
  • 2
2

Add import React from 'react'; to the top of your file.

You are using JSX syntax <MessageBox app={app}/>, which transpiles into React.createComponent(...). In order for this to work React variable must be defined in the scope of the file.

user3707125
  • 3,394
  • 14
  • 23
2

Try sth like this;

import React from 'react';
import App from './containers/App';
import enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
enzyme.configure({ adapter: new Adapter() });

describe('App Screen', () => {
  let mountedAppScreen;
  let props;

  const appScreen = () => {
    if (!mountedAppScreen) {
      mountedAppScreen = enzyme.mount(
        <App {...props} />
      );
    }
    return mountedAppScreen;
  }
  it("it always renders div", () => {
    const divs = appScreen().find("div");
    expect(divs.length).toBeGreaterThanOrEqual(1);
  });
});
Tolga D.
  • 91
  • 3
  • 9
1

Using the latest version of the libraries, I've faced the same error reported in every answer of this question. Error: TypeError: Adapter is not a constructor.

I've grouped all the necessary steps in order to proper test your ReactJS component using Enzyme (I've used Jest but it might work with Mocha as well, in that case, just switch the main test package):

1) Libraries (package.json):

"dependencies": {
    "jest": "^24.6.0",
    (...)
}
"devDependencies": {
    "chai": "^4.2.0",
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.7.0",
   (...)
}

2) TEST SETUP: You can setup the Enzyme in every test. But as type_master_flash wisely suggested, you can add a script to do that. In order to do so, create a new setting in your package.json file at the same level of the sessions scripts, dependencies, etc:

Jest Version 23.x (or previous):

"devDependencies": { 
     (...) 
 },
"jest": {
    "setupTestFrameworkScriptFile": "./tests.setup.js"
 },

After Jest 24.0 version: According to Jest Documentation, "setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv".

"devDependencies": { 
     (...) 
 },
"jest": {
    "setupFilesAfterEnv": ["./tests.setup.js"]
 },

This file can be anywhere you prefer and you can name it as you wish. Just remember to setup the proper file location. In the current example I've stored my file in the root of my project.

3) tests.setup.js: As I've discovered in Enzyme: TypeError: Adapter is not a constructor, the problem here is that we cannot "import '' a module with a default export". The proper way of configuring your file is:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

Just that and you are good to test your components.

Cheers and hope this helps.

Daniel Santana
  • 1,493
  • 20
  • 19
  • Not sure if 2) TEST SETUP is still viable. Least not if the React App is 'Out of the box'. You get errors like: `These options in your package.json Jest configuration are not currently supported by Create React App: • setupTestFrameworkScriptFile` – Daedalus May 05 '19 at 20:18
  • 1
    Well observed @Daedalus. I will update my answer with the latest version. Thank you – Daniel Santana May 06 '19 at 21:17
0

For everyone who read this in the future, setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv by the documentation, in new versions. We can add our file like this:

"setupFiles": [
    "<rootDir>/src/setupTests.js"
]
irandoust
  • 542
  • 6
  • 12
0

I faced the same error and for some reason React wasn't picking up setupTests.js file automatically.

I created a new file called jest.config.js at the root directory and added

{ "jest": { "setupTestFrameworkScriptFile": "<rootDir>/path/to/your/file.js", } }

After this, error disappeared.

Note: Later on, I removed the jest.config.js file but it still works now.

Not sure what was actually causing the problem though!

Purnima
  • 129
  • 7
0

The file configuration must be in setupFilesAfterEnv property of jest.config.js

{
  ...
  setupFilesAfterEnv: ["<rootDir>/jest.transform.js"],
  ...
}
Michalis Garganourakis
  • 2,872
  • 1
  • 11
  • 24
0

If anyone comes across this while trying to fix this after setting up Testing React Components with Jest in GatsbyJs (https://www.gatsbyjs.org/docs/testing-react-components/)

In the setup-test-env.js you make, edit it to look like this:

import "@testing-library/jest-dom/extend-expect"
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

configure({ adapter: new Adapter() })
Neil Morgan
  • 626
  • 4
  • 17
0

Create a file named setupTests.js in the root of your project. jest will automatically look for this file before running any test suits. Add the following content to the file.

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

Note: the filename should be exactly the same.no need to import this setupTests.js file into your test files.it will work automatically

yasarui
  • 6,209
  • 8
  • 41
  • 75
0

For those who use VS Code and the Jest Runner extension for a React CRA app, don't forget to configure Jest Runner to use CRA's built in script runner by setting the jest command to:

npm test -- --watchAll=false

You will get the error in topic if you forget to do that. And since you are using CRA you won't be able to configure setupFilesAfterEnv in package.json nor jest.config.js. Trying that will result in this error:

These options in your package.json Jest configuration are not currently supported by Create React App

Dennis Persson
  • 843
  • 7
  • 23
0
  1. npm i enzyme-adapter-react-16 enzyme-to-json --save-dev

  2. Add to package.json enter image description here

"jest": {
       "collectCoverageFrom": [  "src/**/*.js", "!src/index.js" ]
};
  1. Add two files to src folder ->
  • setupTests.js

  • tempPolyfills.js

  1. setupTests.js :
import requestAnimationFrame from './tempPolyfills';

        import { configure } from "enzyme";
        import Adapter from 'enzyme-adapter-react-16';

        configure({adapter: new Adapter(), disableLifecycleMethods:true});
  1. tempPolyfills.js:
const requestAnimationFrame = global.requestAnimationFrame = callback => {
          setTimeout(callback,0);
      };
export default requestAnimationFrame;
  1. in case shallow -> expect() fails in test case use toJson() : Example :
    import { shallow } from "enzyme";
    import App from "./App";
    import toJson from 'enzyme-to-json';
    describe('App', () => {
        const app = shallow(<App />);
        it('renders correctly', () => {
            expect(toJson(app)).toMatchSnapshot();
        });
     });
0

If you think you've otherwise setup everything correctly (e.g. have the @wojtekmaj/enzyme-adapter-react-17 for React 17 support installed), one more pitfall to check with Typescript:

Do you have

"esModuleInterop": true,

and the matching import format for the adapter?

import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import Enzyme from 'enzyme';
blub
  • 8,757
  • 4
  • 27
  • 38