reactjs - 如何在 React/Redux/Jest 测试中的异步调用后测试方法调用
问题描述
我的组件有一个调用方法“handleSave”的按钮。我简化了代码以使其更具相关性。
该组件方法如下所示:
handleSave = async () => {
const response = await this.props.dispatchSave();
this.props.dispatchNotification();
}
我的测试:
let dispatchSave = jest.fn().mockResolvedValue({});
let dispatchNotification = jest.fn().mockReturnValue('Saved!');
it('should dispatch actions', () => {
const component = mount(<Comp dispatchSave={dispatchSave} dispatchNotification={dispatchNotification}>);
const instance = component.find(Comp).instance() as Comp;
instance.handleSave();
expect(dispatchSave).toHaveBeenCalled();
expect(dispatchNotification).toHaveBeenCalledWith('Saved!');
});
第一个断言有效,但第二个调度永远不会被断言,因为它出现在异步调用之后(如果我将它移到上面,它会起作用)。
如何在异步调用后断言方法调用?
解决方案
如果this.props.dispatchNotification
返回一个承诺(或者你可以让它返回一个承诺),那么你可以在handleSave
调用中返回这个结果。
handleSave = async () => {
const response = await this.props.dispatchSave();
return this.props.dispatchNotification();
}
在测试中,您需要为您的函数调用it
添加async
关键字和前缀。await
it('should dispatch actions', async () => {
const component = mount(<Comp dispatchSave={dispatchSave} dispatchNotification={dispatchNotification}>);
const instance = component.find(Comp).instance() as Comp;
await instance.handleSave();
expect(dispatchSave).toHaveBeenCalled();
expect(dispatchNotification).toHaveBeenCalledWith('Saved!');
});
推荐阅读
- php - 如何在 Yii2 GridView 中显示分页?
- javascript - jQuery ondrop 总是将元素一个接一个地放置在特定的位置,而不是确切的发布位置
- javascript - 在 node.js 中为每个用户分配一个变量
- c++ - 给定目标名称列表,如何获取目标文件名列表?
- bash - 如何自动完成特定目录下的文件?
- javascript - 在另一个 React 项目中作为依赖项安装时,自定义 React 组件库不加载 CSS
- html - 使用 Django 模板逻辑来确定对象是否被显示
- flutter - 容器以匹配来自 url 的图像高度
- google-cloud-platform - 使用印度信用卡的帐单帐户
- python - opencv 绘制矩形函数在 C++ 和 python 中的行为不同