React Enzyme Test with Multiple Nodes

1 minute read

As you write your React application, you’ll (hopefully) start to test your components. If you used the $ npx create-react-app installation, then you’re already setup for running tests. However, you’ll notice when testing components that you will probably want to test them in isolation. That’s where AirBnb’s Enzyme plugin comes in.

Enzyme provides a Jquery-like syntax that lets you shallow test your components: instead of rendering all child nodes down to the lowest DOM elements, you can just render the first level node. This provides more isolated testing in that you’ll only have to setup for the component that you’re testing, not all the transitive components that it uses.

Suppose we have a <FooList /> component which takes messages, an array of strings, and wraps them in <Foo /> components:

// FooList.js
import React from 'react';

const FooList = ({ messages }) => {
  messages.map( (message, idx) => (
    <Foo key={ idx } message={ message } />
  ));
};

export default FooList;

We’ll write a test for our <FooList /> component. Most enzyme test functionality expects there to be a single node for doing assertions. In this case, we’ll have a node for each <Foo /> element. We’ll want to verify that each <Foo /> message matches, we’ll use the at(your_zero_based_index) to get the node in the wrapper individually.

//Foo.test.js
import React from 'react';
import { shallow } from 'enzyme';
import FooList from './FooList';
import Foo from './Foo';

describe('<FooList />', () => {
  it('should render several <Foo />', () => {
    const messages = ['message 1', 'message 2'];
    const fooWrapper = shallow(<FooList messages={ messages } />).find(Foo);

    /* There should be a <Foo /> for each message */
    expect(fooWrapper).toHaveLength(messages.length);

    /* Each message should be passed to <Foo /> */
    expect(fooWrapper.at(0)).toHaveProperty('message', messages[0]);
    expect(fooWrapper.at(1)).toHaveProperty('message', messages[1]);
  });
});

There are ways to make this code less redundant and cleaner, but it should demonstrate the use of at(...) and also show how to check the property of components using toHaveProperty(...).

Updated:

Leave a Comment