我有以下功能代码:
fetchDeviceList是在mapStateToProps的帮助下从redux存储绑定的
componentDidMount() {
this.props.fetchDeviceList().then(() => {
this.saveFirstClassifiedDeviceDetails();
});
}
我的测试代码如下所示:
it('should pass', () => {
const methodNameFake = jest.spyOn(
DeviceListContainer.prototype,
'fetchDeviceList'
);
const props = {
data: []
};
const connectedComponent = mount(
<DeviceListContainer {...props} />
);
expect(methodNameFake).toHaveBeenCalledTimes(1);
});
但是出现错误为: TypeError: this.props.fetchDeviceList is not a function
TypeError: Cannot read property '_isMockFunction' of undefined
fetchDeviceList
是从redux直接通过绑定的功能 mapStateToProps
我需要了解测试此实现的最佳方法是什么?我是React的新手,这是第一次尝试为承诺编写Jest测试用例,请耐心尝试错误。
也尝试过;
component = shallow(
<DeviceListContainer
{...props}
fetchDeviceList={jest.fn().mockReturnValue(() => {
return Promise.resolve('yo');
})}
/>
);
然后我得到错误为: TypeError: this.props.fetchDeviceList(...).then is not a function
我们是否需要在测试时通过道具,这是正确的处理方式,因为一旦从Redux存储中挂载了组件,就会生成道具数据。最好的方法是什么?
有人了解我在做什么错吗?
Redux文档中有关于测试Redux容器的部分。
https://redux.js.org/recipes/writing-tests#connected-components
在上面的链接中已经提到了它,但我建议您仅测试内部表示组件,而不要尝试测试Reduxconnect()
函数返回的高阶组件。
您对您编写的单元测试代码(即内部表示组件)感兴趣,而不是Redux团队编写的由call产生的代码connect()
。
因此,只要您直接进行测试DeviceList
,而不是对容器进行测试,就可以使用已经存在的方法:
component = shallow(
<DeviceList
data={[]}
fetchDeviceList={jest.fn().mockReturnValue(() => {
return Promise.resolve('yo');
})}
/>
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句