我有以下功能代码:
fetchDeviceList 在 mapStateToProps 的帮助下从 redux store 绑定(bind)
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 的新手,这是第一次尝试为 promises 编写 Jest 测试用例,请原谅错误。
也试过;
component = shallow(
<DeviceListContainer
{...props}
fetchDeviceList={jest.fn().mockReturnValue(() => {
return Promise.resolve('yo');
})}
/>
);
然后我得到错误:TypeError: this.props.fetchDeviceList(...).then is not a function
我们是否需要在测试时传递 props,这是正确的处理方式吗,因为 props 数据将在组件从 Redux store 挂载后立即生成。最好的方法是什么?
有人知道我做错了什么吗?
最佳答案
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');
})}
/>
);
关于javascript - 使用 mapStateToProps Jest 测试 promise 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51550520/