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?
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):
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:
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:
Just that and you are good to test your components.
Cheers and hope this helps.
Add it to your test case file.
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:
Try sth like this;
Add
import React from 'react';
to the top of your file.You are using JSX syntax
<MessageBox app={app}/>
, which transpiles intoReact.createComponent(...)
. In order for this to workReact
variable must be defined in the scope of the file.You need to use the import like this:
This way: (import * as Adapter from ...) returns a message "TypeError: Adapter is not a constructor."