【发布时间】:2018-10-24 23:27:23
【问题描述】:
我在我的应用程序中使用 React。我正在我的componentDidMount 中进行 API 调用,但它是有条件的。我在组件中的代码是
componentDidMount() {
if (!this.props.fetch) {
fetchAPICall()
.then(() => {
/** Do something **/
});
}
}
我把测试写成:
it('should not fetch ', () => {
const TFCRender = mount(<Component fetch />);
const didMountSpy = jest.spyOn(TFCRender.prototype, 'componentDidMount');
expect(didMountSpy).toHaveBeenCalledTimes(1);
expect(fetchAPICall).toHaveBeenCalledTimes(0);
});
测试给我带来了错误
TypeError: Cannot read property 'componentDidMount' of undefined
我做错了什么以及测试这种情况的正确方法是什么。
【问题讨论】:
-
你必须模拟
fetchAPICall并测试它是否被调用 -
检查一次,它可能会有所帮助stackoverflow.com/questions/43245040/…
标签: javascript reactjs enzyme jestjs