Enzyme is a JavaScript testing utility for React by AirBnB that makes it easier to test by providing functions to help you assert, manipulate, and traverse your React components.

It has documentation for how to use Enzyme with mocha, karma, jasmine, browserify, webpack, and more!

In this post, we are going to use Mocha as our testing library, since Enzyme was originally designed to work with Mocha.

Getting Started with Enzyme

Starting with Enzyme is really simple thanks to NPM:

npm install --save-dev enzyme

Let’s make simple counter app where we have a component with a plus button and a counter. Whenever we press the button, the counter should increase.

We start by writing our test – we might as well practice TDD while we are at it.

import React from 'react';
import { shallow } from 'enzyme';
import { Counter } from './counter.jsx';

describe('counter', () => {
  it( 'has a button', () => {
    const wrapper = shallow(<Counter />);
    expect(wrapper.find('button')).to.have.length(1);
  });

  it( 'starts with 0', () => {
    const wrapper = shallow(<Counter />);
    expect(wrapper.find('span')).to.have.length(1);
    expect(wrapper.find('span').text()).to.contain("0");
  });

  it( 'increments', () => {
    const wrapper = shallow(<Counter />);
    wrapper.find('button').simulate('click');
    expect(wrapper.find('span').text()).to.contain("1");
  });
});

When you run the tests, they will all fail. Let’s change that by writing our React component!

import React from 'react';

const Counter = React.createClass({
  getInitialState() { return { counter: 0 }; },

  onClick() {
    this.setState({ counter: this.state.counter + 1 });
  },

  render() {
    return (
      <div>
        <span>{this.state.counter}</span>
        <button onClick={this.onClick}>Increment</button>
     </div>
    );
  }
});

export { Counter };

Awesome! Our tests should now pass!

What Can Enzyme Test?

Enzyme can help with what is called shallow rendering – you can test only your own component, and not accidentally its child components. This lets you find elements within your component using selectors, checking for text, number of occurrences, and whether different methods and life-cycle methods were fired.

It also lets you do full DOM rendering as well. This will render the entire tree of components you pass to it, which is useful for testing that props were passed correctly.

Enzyme really shines when you are working with React. Unit testing your UI components and simulating events can really help make sure your app is staying on track.