You may have already npm installed Jest into your React project, or you may have started your React project in something like create React app that already comes with Jest. Heres how you can do that.
First you want to npm install enzyme and enzyme-adapter-react-16
npm install –save-dev enzyme enzyme-adapter-react-16
Next you want to create a file that holds the following code:
// enzyme.js
import Enzyme, { configure, shallow, mount, render } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
export { shallow, mount, render };
export default Enzyme;
Note that we’re exporting shallow, mount and render which we will import in our *.test.jsx file.
Lets create a component that we will test
//testcomponent.jsx
import React from 'react';
export default function TestComponent(props) {
return (
<div>
I am a test component!
</div>
);
}
Now let’s create our test file and import React, our component and our three enzyme functions. We’ll use the shallow function to shallow render our component.
We’ll also write a test that just checks to see if the component exits.
// testcomponent.test.jsx
import React from 'react';
import TestComponent from '.';
import { shallow, mount, render } from '../enzyme';
describe('<TestComponent/>', () => {
it('enzyme test', () => {
const wrapper = shallow(<TestComponent/>);
expect(wrapper.exists()).toBe(true);
});
}