React enzyme testing, Cannot read property 'have' of undefined

Toby picture Toby · Jul 26, 2016 · Viewed 31.6k times · Source

I'm writing a test using Enzyme for React.

My test is extremely straightforward:

import OffCanvasMenu from '../index';
import { Link } from 'react-router';

import expect from 'expect';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';
import React from 'react';

describe('<OffCanvasMenu />', () => {
  it('contains 5 <Link /> components', () => {
    const wrapper = shallow(<OffCanvasMenu />);
    expect(wrapper.find(<Link />)).to.have.length(5);
  });
});

This code is basically taken directly from airbnb/enzyme docs, but returns the error:

FAILED TESTS:
  <OffCanvasMenu />
    ✖ contains 5 <Link /> components
      Chrome 52.0.2743 (Mac OS X 10.11.6)
    TypeError: Cannot read property 'have' of undefined

I'm a little unclear on what I'm doing differently from the docs. Any guidance greatly appreciated.

Answer

Ori Drori picture Ori Drori · Jul 26, 2016

Use Link instead of <Link />:

describe('<OffCanvasMenu />', () => {
  it('contains 5 <Link /> components', () => {
    const wrapper = shallow(<OffCanvasMenu />);
    expect(wrapper.find(Link)).to.have.length(5);
  });
});

It appears in the 1st example in the airbnb/enzyme docs:

it('should render three <Foo /> components', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.find(Foo)).to.have.length(3);
});

The syntax .to.have.length is for the Chai Assertion Library. For Jest use .toHaveLength:

it('should render three <Foo /> components', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.find(Foo)).toHaveLength(3);
});