I'm trying to write a unit test to check that a function (passed as a prop) gets called if another prop is true in useEffect hook. The unit test fails to confirm that the (mocked) function is called in the useEffect hook, but it can confirm that a function that is spyOn from an imported module is called. Does anyone know what might be the issue? Thanks!
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 />)
});
Unit test:
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
});
It seems like it has something to do with the useCallback with useEffect. If I remove the useCallback and add the logic within to useEffect, it can capture someReduxDispatchFuncMock has been called.