我正在使用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
对于与文档有何不同,我尚不清楚。任何指导,不胜感激。
最佳答案
使用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 Assertion Library。对于Jest,请使用.toHaveLength
:it('should render three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).toHaveLength(3);
});
关于testing - react enzyme 测试,无法读取未定义的属性 'have',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38596834/