56

我正在使用Enzyme for React 编写测试。

我的测试非常简单:

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

此代码基本上直接取自airbnb/enzyme docs,但返回错误:

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

我有点不清楚我在做什么与文档不同。非常感谢任何指导。

4

4 回答 4

52

使用Link代替<Link />

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

它出现在 airbnb/enzyme 文档的第一个示例中:

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

该语法.to.have.length适用于Chai 断言库开玩笑使用.toHaveLength:_

it('should render three <Foo /> components', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.find(Foo)).toHaveLength(3);
});
于 2016-07-26T18:07:35.167 回答
39

在他们的文档中 Enzyme 使用 Chai 断言,所以如果你想使用expect(***).to.have.length(***)你需要安装chai-enzyme和使用它的expect. 因此,如果您使用 Jest 快照,它会导致问题expect(***).toMatchSnapshot(),但本文将帮助您解决它,因此您可以同时使用这两种方法。

于 2017-12-10T13:55:27.657 回答
11

这可能是因为您没有在依赖项中安装 chai 断言库,或者没有在测试文件中导入它。因此,您需要安装 chai-enzyme 并将其导入您的测试文件中,即

npm 安装柴

从'chai'导入{期望};

于 2018-03-19T16:58:39.240 回答
3

当括号放错位置以致.to.have错误地放置在 的括号内时,可能会发生此错误expect(...)

正确的:

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

导致TypeError: Cannot read property 'have' of undefined

expect(wrapper.find(<Link />).to.have.length(5));
于 2018-03-15T20:12:15.773 回答