I'm trying to test a relatively simple custom hook that uses useEffect and setTimeout. However, my test fails, and I cannot figure out what is wrong.
Here is the hook itself(useTokenExpirationCheck.ts)
import { useEffect } from 'react';
import { logout } from '../features/profile/profileSlice';
import { useAppDispatch } from '../store/hooks';
export default function useTokenExpirationCheck(exp: number): void {
const dispatch = useAppDispatch();
useEffect(() => {
if (exp) {
const timeToLogout = exp * 1000 - Date.now();
setTimeout(() => {
dispatch(logout());
}, timeToLogout);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [exp]);
}
and my testing file:
import { act, renderHook } from '@testing-library/react-hooks';
import useTokenExpirationCheck from './useTokenExpirationCheck';
jest.mock('../features/profile/profileSlice');
const logout = jest.fn();
const exp = Date.now() + 6000;
describe('Expiration token', () => {
test('should logout user', async () => {
jest.useFakeTimers();
act(() => {
renderHook(() => {
useTokenExpirationCheck(exp);
});
});
expect(logout).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(60000);
expect(logout).toHaveBeenCalledTimes(1);
});
});
What I know is that the exp variable is somehow not passed to the useTokenExpirationCheck function (console.log showed me 0 inside of the function, when it was executed). So basically, I am not even getting to the useEffect itself... any ideas what could go wrong?