Check if child component rendered - Jest, Enzyme

darKnight picture darKnight · Jun 21, 2018 · Viewed 24.8k times · Source

In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});

Parent:

const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (
    <div>
      <div className={style.planet_container}>
        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}
      </div>
    </div>
  );
});

Above code is taken from here, but it's not working. I am getting the following error:

Expected 1, Received 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.

Answer

Ekown picture Ekown · Feb 15, 2020

You can check whether a parent component has rendered its child component using containsMatchingElement().

Based on Enzyme docs:

Returns whether or not a patternNode react element matches any element in the render tree.

Your test should look like this:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.containsMatchingElement(<Child />)).toEqual(true);
  });
});