I have a custom hook that dispatches an action when a URL parameter changes:
export const useUser = (): void => {
const dispatch = useDispatch();
const { user } = useParams<{ user: string }>();
useEffect(() => {dispatch(getUser(user));
}, [dispatch, user]);
};
I have a test that mocks useDispatch and useParams:
const dispatch = jest.fn();
const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch').mockImplementation(() => {
return dispatch;
});
const useParamsSpy = jest.spyOn(reactRouter, 'useParams').mockImplementation(() => {
return { user: 'test' };
});
const getUserSpy = jest.spyOn(slice, 'getUser');
renderHook(() => useRequestProfile());
expect(getUserSpy.mock.calls).toEqual([['test']]);
Now, this works, in that I can determine that getUser('test') has been called, but the point of wrapping it in useEffect is to make sure that it only get's called once. How can I test this?