【问题标题】:React enzyme testing, Cannot read property 'have' of undefined反应酶测试,无法读取未定义的属性“拥有”
【发布时间】:2016-11-30 12:17:41
【问题描述】:

我正在使用 Enzyme 为 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

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

【问题讨论】:

    标签: testing reactjs enzyme


    【解决方案1】:

    使用Link 代替&lt;Link /&gt;

    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 Assertion Library。对于Jest,请使用.toHaveLength

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

    【讨论】:

    • 感谢您的回复 - 我看到与 Link 相同的错误。而且我正在关注文档,尽管我使用的代码导入 Michael Jackson 的 expect,但我不确定这是否会被抛弃(我也检查了那里的文档)。
    • 你使用什么断言库?试试这个 - console.log('length', wrapper.find(Link).length);,看看控制台中会出现什么。
    • 所以酶工作正常。试试这个 - expect(wrapper.find(Link).length).toBe(5);。如果您使用的是 expect,请不要使用 chai,它们正在做同样的事情。
    • @Mihir to.have.length 是 chai 语法的一部分,而 .toBe(5) 是 expect 语法的一部分。所以这取决于你使用什么断言。
    • @OriDrori 终于通过了我的测试,非常感谢!花了几个小时在这上面,并通过酶文档。谢谢!!
    【解决方案2】:

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

    【讨论】:

    • 谢谢——这对我们这些不认识所有不同库语法的新手很有帮助!
    【解决方案3】:

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

    npm install chai

    从'chai'导入{期望};

    【讨论】:

    • 酶文档没有对此进行更多说明。有没有更好的使用酶、柴和摩卡进行 reactjs 单元测试的教程?
    • hmmm.... 对于这些测试库,它有一个非常糟糕的文档。 plp 混合它们,但它们的文档不考虑任何依赖项
    【解决方案4】:

    如果括号放错了位置,导致.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));
    

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 2017-09-24
      • 2017-06-16
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      相关资源
      最近更新 更多