Closed
Description
Hey there! I'm having an issue testing a custom hook that uses an async function in the useEffect hook. If I try to await a promise inside of the run
function, my test times out if I use waitForNextUpdate
. What am I doing wrong and how can I fix this behavior?
import { renderHook, act } from '@testing-library/react-hooks';
import { useState, useEffect, useContext } from 'react';
// using fake timers
jest.useFakeTimers();
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const run = async () => {
// await Promise.resolve(); // If I remove this line, test passes.
setTimeout(() => {
setCount(count => count + 1);
}, 5000);
};
run();
}, []);
return { count };
}
test('it should work', async () => {
const { result, waitForNextUpdate } = renderHook(() => Counter());
act(() => {
jest.runAllTimers();
});
// await waitForNextUpdate(); this line triggers the Jest 5000ms timeout error.
expect(result.current.count).toEqual(1);
});