【发布时间】:2021-01-07 04:17:49
【问题描述】:
我正在尝试编写一个单元测试来检查一个函数(作为一个 prop 传递)是否在 useEffect 钩子中另一个 prop 为 true 时被调用。单元测试无法确认在 useEffect 挂钩中调用了(模拟的)函数,但可以确认调用了来自导入模块的 spyOn 函数。有谁知道可能是什么问题?谢谢!
import {getUser} from './Auth';
export function ComponentA({
shouldRetryExport,
someReduxDispatchFunc,
}) {
const handleExport = useCallback(async () => {
const user = await getUser();
someReduxDispatchFunc();
}, []);
useEffect(() => {
if (shouldRetryExport) {
handleExport();
}
}, [shouldRetryExport]);
return (<SomeComponent />)
});
单元测试:
import * as Auth from './Auth';
it('should call someReduxDispatchFunc if getUserAuthorization is true', () => {
const getAuthUserSpy = jest.spyOn(Auth, 'getUser');
const someReduxDispatchFuncMock = jest.fn();
const props = {
someReduxDispatchFunc: someReduxDispatchFuncMock,
shouldRetryExportWithUserReAuthorization: true,
};
enzyme.mount(<ComponentA {...props} />);
expect(getAuthUserSpy).toHaveBeenCalled(); // works -> returns true
expect(someReduxDispatchFuncMock).toHaveBeenCalled(); // doesn't work -> returns false
});
似乎它与useCallback和useEffect有关。如果我删除 useCallback 并将其中的逻辑添加到 useEffect 中,它可以捕获 someReduxDispatchFuncMock 已被调用。
【问题讨论】:
-
将
someReduxDispatchFuncSpy更改为someReduxDispatchFuncMock -
对不起@slideshowp2 - 它实际上已经是 someReduxDispatchFuncMock 了。我在提供的示例中有错字。谢谢!
标签: reactjs unit-testing jestjs react-hooks enzyme