我有一个 React hook 组件,onChange 事件将执行 aync-await 函数和一些调度,在我的模型测试中,如果我放置我的,则不会检测到调用 store.dispatch
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
当我运行我的应用程序时,上述 3 种情况之间没有真正的 UI 行为差异,都发生了调度以及我的等待函数,但我有点困惑,为什么我的测试用例无法检测到我的 dispatch ?是否有办法绕过或强制解决测试用例中的等待方法?
最佳答案
您必须考虑到 await
用于等待异步任务。因此,当您在 async
方法中调用 await
时,后面的代码将不会执行,直到异步任务解决为止。
很可能,您没有在测试代码中等待异步代码解析。这会导致 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)
});
关于javascript - React async wait 函数按执行顺序阻止 useDispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61551452/