【发布时间】:2017-12-14 02:45:59
【问题描述】:
在我的 React 应用程序(无通量/redux)中,我正在尝试使用 enzyme 对组件进行单元测试,浅渲染效果很好,我能够检索它的状态等等,但是mount rendering给我一个cannot read property 'route' of undefined的错误。
我的App.js 看起来像这样
class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<MyCustomLayout>
<Route path="/mypath" component={myComponent} />
</MyCustomLayout>
</Switch>
</BrowserRouter>
)
}
这是myComponent的代码
import React, { Component } from 'react';
import './index.css';
import { getList } from './apiService.js';
class myComponent extends Component {
constructor(props) {
super(props);
this.state = {
myList: [],
};
}
componentDidMount() {
// get list ajax call
getList().then(response => {
this.setState({
myList: response.data
})
});
}
handleClick = () => {
this.props.history.push('/home');
}
renderMyList() {
/*
Code for rendering list of items from myList state
*/
}
render() {
return (
<div>
<h1>Hello World</h1>
<button onClick={this.handleClick}>Click me</button>
{this.renderMyList()}
</div>
)
}
}
export default myComponent
这是我的测试代码
import React from 'react';
import myComponent from './myComponent';
import renderer from 'react-test-renderer';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';
test('Initial state of myList should be empty array ', () => {
const component = shallow(<myComponent/>);
expect(component.state().myList).toEqual([]);
});
test('Make sure the componentDidMount being called after mount', () => {
sinon.spy(myComponent.prototype, 'componentDidMount');
const component = mount(<myComponent/>);
expect(myComponent.prototype.componentDidMount.calledOnce).toEqual(true);
});
错误是什么?
【问题讨论】:
-
您应该使用
MemoryRouter而不是BrowserRouter进行单元测试。您的问题可能与此有关。你能展示一下你的测试代码吗? -
那么你的意思是我应该为了单元测试而改变真正的实现?我不认为这是一个好主意。反正我加了测试,请看@LukeVella
-
看看
myComponent中的内容会很有用。 -
@LukeVella 再次编辑
-
我什么也没看到,但你一定是在某个地方指的是
route。也许发布错误的堆栈跟踪。
标签: unit-testing reactjs enzyme