javascript - React async await 功能块 useDispatch 按执行顺序
问题描述
我有一个 React 钩子组件,onChange 事件将执行 aync-await 函数和一些调度,在我的模型测试中,store.dispatch
如果我将我放在await function
任何调度之前,它不会被检测到被调用,它只会检测到被调用,如果我将调度放在等待函数之前,例如
const onChange = async (userId) => {
await someAsyncFn(userId);
dispatch(selectUser(userId)); //not detected
dispatch(selectGroup(userId); //not detected
};
--Test.js
expect(store.dispatch).toHaveBeenCalledTimes(2) ---failed, only receive 0 times
但是如果我在调度后放置了等待,则测试用例通过了
const onChange = async (userId) => {
dispatch(selectUser(userId)); //detected
dispatch(selectGroup(userId); //detected
await someAsyncFn(userId);
};
--Test.js
expect(store.dispatch).toHaveBeenCalledTimes(2) ---passed receive 2 times
但是,如果我在调度之间放置了等待,则只会检测到上面的调度
const onChange = async (userId) => {
dispatch(selectUser(userId)); //detected
await someAsyncFn(userId);
dispatch(selectGroup(userId); //not detected
};
--Test.js
expect(store.dispatch).toHaveBeenCalledTimes(2) ---failed, only detect selectUser being called
当我运行我的应用程序时,上述 3 种情况之间的 UI 行为没有真正的区别,调度和我的等待函数都发生了,但我有点困惑,为什么我的测试用例无法检测到我的调度?反正有没有绕过或强制从测试用例中解决我的等待方法?
解决方案
您必须考虑await
用于等待异步任务的情况。因此,当您await
在async
方法中调用时,在异步任务解决之前,后面的代码不会执行。
很可能,您没有在测试代码中等待异步代码解析。await
这会导致您的测试中不会考虑之后的所有内容。
要等待异步代码解析,您必须将您的测试定义async
为您的测试await
方法:
test('testing on change', async () => {
// Perform the call to the onChange method. Await for it to resolve.
await onChange();
// At this point, the calls to dispatch will have been done independently of their order in the onChange method.
expect(store.dispatch).toHaveBeenCalledTimes(2)
});
推荐阅读
- python - ValueError:检查目标时出错:预期 dense_3 具有 2 个维度。但我指定dense_3 有1维
- reactjs - 如何使用 Apollo Graphql 客户端和 React 解决“TypeError:无法读取未定义的属性“参数”?
- android - Kotlin 循环泛型
- python-3.x - 使用 Try 进行 Web 抓取:除了:在 For 循环中
- android - 如何同时设置导航栏和状态栏 Light 主题
- sql - 插入数据:查看哪一列导致 Redshift 上的数字溢出
- websocket - AWS WebSocket API Gateway 模板选择表达式示例
- tensorflow - Tensorflow Lite 转换失败:占位符操作中不支持的数据类型
- ios - ios应用在后台时的内存管理
- sql - 如何根据sql中的外键从表中获取数据