Enzyme is a JavaScript testing utility for React that asserts, manipulates, and traverses React Components' output.
Setup with Jest & React 16
// test/setup.js
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
Rendering Modes
Shallow Rendering (shallow)
Renders only the current component one level deep without rendering child components:
import { shallow } from 'enzyme';
const wrapper = shallow(<MyComponent title="Hello" />);
expect(wrapper.find('h1').text()).toEqual('Hello');
Full DOM Mounting (mount)
Renders component along with all children into a headless jsdom document:
import { mount } from 'enzyme';
const wrapper = mount(<MyComponent />);
expect(wrapper.find('.child-node')).toHaveLength(2);
wrapper.unmount();
DOM Traversal & Finders
wrapper.find('button') // Find by CSS selector or Component type
wrapper.filter('.active') // Filter current selection
wrapper.not('.hidden') // Inverse filter
wrapper.children() // Get child nodes
wrapper.parent() // Get direct parent
wrapper.closest('form') // Find closest ancestor
wrapper.first() // First matching node
wrapper.last() // Last matching node
wrapper.at(0) // Nth matching node
Simulating Events
// Click event
wrapper.find('button').simulate('click');
// Change event with mock event payload
wrapper.find('input').simulate('change', {
target: { value: 'New text' }
});
// Keydown event
wrapper.find('input').simulate('keydown', { keyCode: 13 });
State, Props & Context
// Read values
wrapper.state('loading'); // Read state key
wrapper.prop('disabled'); // Read prop value
wrapper.props(); // Full props object
// Mutate values in tests
wrapper.setState({ count: 5 });
wrapper.setProps({ active: true });
// Access underlying React instance
const instance = wrapper.instance();
Assertions & Element Checks
expect(wrapper.exists()).toBe(true);
expect(wrapper.hasClass('btn-primary')).toBe(true);
expect(wrapper.contains(<span className="badge">New</span>)).toBe(true);
expect(wrapper.text()).toContain('Welcome');
expect(wrapper.html()).toContain('class="active"');