首页 > 解决方案 > 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 行为没有真正的区别,调度和我的等待函数都发生了,但我有点困惑,为什么我的测试用例无法检测到我的调度?反正有没有绕过或强制从测试用例中解决我的等待方法?

标签: javascriptasync-awaitjestjsreact-hooksenzyme

解决方案


您必须考虑await用于等待异步任务的情况。因此,当您awaitasync方法中调用时,在异步任务解决之前,后面的代码不会执行。

很可能,您没有在测试代码中等待异步代码解析。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)
});

推荐阅读