在执行顺序中反应异步等待功能块useDispatch

时间:2020-05-01 22:00:45

标签: javascript async-await jestjs react-hooks enzyme

我有一个React钩子组件,onChange事件将执行aync-await函数和一些调度,在我的模型测试中,如果放置store.dispatch,则未检测到await function被调用在任何调度之前,如果我将调度放在await函数之前,它只会检测到被调用,例如

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

当我运行我的应用程序时,以上三种情况之间没有真正的UI行为,既发生了调度也发生了我的await函数,但是我有点困惑,为什么我的测试用例无法检测到我的调度?是否有任何方法可以绕过或强制从测试案例中解决我的await方法?

1 个答案:

答案 0 :(得分:1)

您必须考虑到await用于等待异步任务。因此,当您在await方法中调用async时,直到异步任务解决后,下面的代码才会执行​​。

很可能,您不是在等待测试代码中等待异步代码来解决。这导致await之后的所有内容都不会在您的测试中予以考虑。

要等待异步代码解析,您必须将被测试方法的测试定义为asyncawait

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)
});