The main problem is that I can't seem to get to the next lines of the code because of an await function in my CustomHook. For context, I have created a function called sleep that looks like this.
export const sleep = (ms: number): Promise<void> =>
new Promise<void>((res) => setTimeout(res, ms));
Now my custom hook looks something like this.
const useCustomHook = () => {
const [sampleState, setSampleState] = useState(null);
const callApiFunction = async () => {
const results = await callApi();
await sleep(500);
if(results.success) {
const secondResults = await callSecondApi();
await sleep(500);
if(secondResults.success) {
setSampleState(secondResults.data); //Should set state to an {}
}
}
}
return {
sampleState,
callApiFunction,
}
}
To create a unit test for this, I'm using @testing-library/react-hooks
.
I've written a test where
it('should do something', async () => {
jest.useFakeTimers()
const {result, waitForNextUpdate} = renderHook(()=> useCustomHook())
// Using act since we won't allow running functions that changes states without act
act(() => {
result.current.callApiFunction();
jest.advanceTimersByTime(500);
})
await waitForNextUpdate()
expect(result.current.sampleState).toEqual(expectedApiResults);
})
The ones above are pretty much simplified but its basically the gist. I've seen other implementations but most of them are using useEffect
which is a bit different from what I want to do.
Also with he implementation above I get "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test." and state is still `null