我有以下功能代码:
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
是直接通过mapStateToProps
我需要了解测试此实现的最佳方法是什么?我是React的新手,这是第一次尝试为实现promise编写Jest测试用例,请忍受错误。
也尝试过
component = shallow(
<DeviceListContainer
{...props}
fetchDeviceList={jest.fn().mockReturnValue(() => {
return Promise.resolve('yo');
})}
/>
);
然后我收到错误消息:TypeError: this.props.fetchDeviceList(...).then is not a function
我们是否需要在测试时通过道具,这是否是正确的处理方式,因为一旦从Redux存储中装入组件,就会生成道具数据。最好的方法是什么?
有人知道我在做什么错吗?
答案 0 :(得分:1)
Redux文档中有一个有关测试Redux容器的部分。
https://redux.js.org/recipes/writing-tests#connected-components
在上面的链接中已经提到过,但我建议您仅测试内部表示组件,而不要尝试测试Redux的connect()
函数返回的高阶组件。
您对编写的单元测试代码(即内部表示组件)感兴趣,而不是Redux团队编写的调用connect()
的代码。
因此,只要您直接测试DeviceList
而不是容器,就可以使用已经存在的东西。
component = shallow(
<DeviceList
data={[]}
fetchDeviceList={jest.fn().mockReturnValue(() => {
return Promise.resolve('yo');
})}
/>
);