Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
});

In their documentation Enzyme is using Chai assertion, so if you want to use expect(***).to.have.length(***) you need to install chai-enzyme and use its expect. It will, therefore, lead to issues with expect(***).toMatchSnapshot() if you use Jest snapshots, but this article will help you to solve it, so you can do both.


This could be because you don't have the chai assertion library installed in your dependencies or have not imported it in your tests file. Therefore, You need to install chai-enzyme and import it in your test file i.e.

npm install chai

import { expect } from 'chai';


This error can happen when you've got a parenthesis misplaced such that .to.have incorrectly is placed within the parenthesis of expect(...):

Correct:

expect(wrapper.find(<Link />)).to.have.length(5);

Causes TypeError: Cannot read property 'have' of undefined:

expect(wrapper.find(<Link />).to.have.length(5));