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 un
The file configuration must be in setupFilesAfterEnv
property of jest.config.js
{
...
setupFilesAfterEnv: ["<rootDir>/jest.transform.js"],
...
}
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.
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() })