Installation
Enzyme should be installed using npm:
npm i --save-dev enzyme
Enzyme can be used with your test runner of choice. All examples in the documentation will be provided using mocha and BDD style chai, although neither library is a dependency of enzyme.
Working with React 0.13
If you are wanting to use Enzyme with React 0.13, but don't already have React 0.13 installed, you should do so:
npm i react@0.13 --save
Next, to get started with enzyme, you can simply install it with npm:
npm i --save-dev enzyme
And then you're ready to go! In your test files you can simply require
or import
enzyme:
ES6:
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
ES5:
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
Working with React 0.14
If you are wanting to use Enzyme with React 0.14, but don't already have React 0.14 and react-dom installed, you should do so:
npm i --save react@0.14 react-dom@0.14
Further, enzyme requires the test utilities addon be installed:
npm i --save-dev react-addons-test-utils@0.14
Next, to get started with enzyme, you can simply install it with npm:
npm i --save-dev enzyme
And then you're ready to go! In your test files you can simply require
or import
enzyme:
ES6:
import { shallow, mount, render } from 'enzyme';
const wrapper = shallow(<Foo />);
ES5:
var enzyme = require('enzyme');
var wrapper = enzyme.shallow(<Foo />);
Working with jsdom & mount
If you plan on using mount
, it requires jsdom. Jsdom requires node 4 or above. As a result, if
you want to use mount
, you will need to make sure node 4 or iojs is on your machine.
Switching between node versions
Some times you may need to switch between different versions of node, you can use a CLI tool called
nvm
to quickly switch between node versions.
To install NVM:
brew install nvm
nvm install 4
Now your machine will be running Node 4. You can use the nvm use
command to switch between the two
environments:
nvm use 0.12
nvm use 4
Preventing tests from failing on old versions
If you are worried about tests not passing on versions of node that don't support jsdom, Enzyme comes with a helper function to wrap your tests in a safety layer such that any tests written inside of that function will be skipped if jsdom is not available. (Note that this is for mocha only).
import { mount, shallow } from 'enzyme';
describe('MyComponent', () => {
describeWithDOM('interaction', () => {
// these tests will get skipped if jsdom is not available...
it('should do something', () => {
const wrapper = mount(<MyComponent />);
// ...
});
});
describe('non-interaction', () => {
// these tests will always run
it('should do something', () => {
const wrapper = shallow(<MyComponent />);
// ...
});
});
});