我有以下 react 测试文件:
1 import React from 'react';
2 import ReactDOM from 'react-dom';
3 import { shallow, mount } from 'enzyme';
4 import { LinkContainer } from 'react-router-bootstrap';
5 import { App } from './App';
6
7 it('renders without crashing', () => {
8 const div = document.createElement('div');
9 ReactDOM.render(<App />, div);
10 });
11
12 it('renders 4 <LinkContainer />', () => {
13 const appWrapper = mount(<App />);
14 expect(appWrapper.find(LinkContainer)).to.have.length(4)
15 });
这是我的 App.js
的一部分文件:
import React, { Component } from 'react';
import { Image, Grid, Media, Navbar, NavItem, Nav, Jumbotron } from 'react-bootstrap';
import { Link } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
class App extends Component {
render() {
return (
<div>
<Navbar fixedTop inverse>
<Grid>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Daniel Rubio</Link>
</Navbar.Brand>
</Navbar.Header>
<Nav pullRight>
<LinkContainer to="/about">
<NavItem>About</NavItem>
</LinkContainer>
<LinkContainer to="/education">
<NavItem>Education</NavItem>
</LinkContainer>
<LinkContainer to="/experience">
<NavItem>Experience</NavItem>
</LinkContainer>
<LinkContainer to="/skills">
<NavItem>Skills</NavItem>
</LinkContainer>
</Nav>
</Grid>
</Navbar>
<div className="contents">
{ this.props.children }
</div>
<Navbar fixedBottom inverse>
<Navbar.Header>
<Navbar.Brand>
<p>Made with React and with EMCAScript6</p>
</Navbar.Brand>
</Navbar.Header>
</Navbar>
</div>
);
}
}
当我运行此测试时,第二个测试失败并出现以下错误:
FAIL src/App.test.js
✓ renders without crashing (24ms)
✕ renders 4 <LinkContainer /> (21ms)
● renders 4 <LinkContainer />
TypeError: Cannot read property 'have' of undefined
at Object.<anonymous> (src/App.test.js:14:93)
at process._tickCallback (internal/process/next_tick.js:103:7)
Test Summary
› Ran all tests related to changed files.
› 1 test failed, 1 test passed (2 total in 1 test suite, run time 0.476s)
我正在关注Jest
教程和Enzyme
教程在这里找到Enzyme 。我基本上所做的就是复制 enzyme 如何覆盖测试。但是,看起来 React 找不到我的 <LinkContainer />
成分。我已经从适当的包中需要它,所以它应该存在,对吗?如有帮助,将不胜感激。
最佳答案
expect()
来自jest不包含任何 .to
属性/匹配器。
这就是为什么当你执行 expect(...).to.have
时会出现 undefined
的原因
该教程使用 mocha和 chai正如您可以在他们的github page中读到的那样
The documentation and examples for enzyme use mocha and chai, but you should be able to extrapolate to your framework of choice.
关于javascript - 为什么这个渲染测试的 react 组件失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40144859/