Test React components with Enzyme

Guido Schmitz
JavaScript Hub
Published in
2 min readMar 19, 2016

A while ago I read about Airbnb’s new React testing utility called Enzyme, so I decided to try it out.

Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components’ output.

I’ve made an example which can be found on Github. I will add more complex test situations to it later.

The situation
We have two components that we want to test.
A BookList component that has a title and renders different books.
A Book component that is just text with the title and author of the book.

I’m using Mocha as test framework with an assertion framework called Chai.

This is what our tests will look like for the BookList component.

describe("BookList", () => {
const books = [
{ title: 'ReactJS for dummies', author: 'Guido Schmitz' },
{ title: 'Redux and ReactJS', author: 'Dan Abramov' }
];

it("display category title", () => {
const wrapper = render(<BookList category="ReactJS" items={books} />);

assert.equal(wrapper.find('h1').text(), 'Books in ReactJS (2)');
})

it("render book items", () => {
const wrapper = render(<BookList items={books} />);

assert.equal(wrapper.find('#items div').length, 2);
});
});

As you can see the API is pretty clean and straight forward.

Enzyme’s render function is used to render React components to static HTML and analyze the resulting HTML structure. This function uses a third-party library called Cheerio that is great at handling parsing and traversing HTML.

We also have a test to check if the text that is rendered by the Book component, does meet our expectations.

describe("Book", () => {
it("display text", () => {
const wrapper = render(<Book author="Dan Abramov" title="Redux and ReactJS" />);

assert.equal(wrapper.text(), 'Redux and ReactJS by Dan Abramov');
});
});

Again. I’m using the render function, because I want to make sure we test our UI and meet the expected HTML output.

Enzyme also has shallow and mount functions.

According to the docs you would use the mount function when you have components that may interact with DOM apis, or may need the full life cycle to fully test the component (ie, componentDidMount etc.).
And you would use shallow to constrain yourself to testing a component as a unit, and to make sure that your tests aren’t indirectly asserting on behavior of child components.

The full code can be found on Github. I will add more examples later with complex test situations using the shallow and mount functions. If you want to contribute, you can open a pull request.

--

--

Guido Schmitz
JavaScript Hub

Product Geek. JavaScript. NodeJS. Loves to share knowledge with others. Co-Founder at Flex-Appeal.