I'm testing a custom hook with react-testing-library
which basically does this:
function useHook() {
const [state, setState] = useState();
const fetch = async () => {
const response = await httpCall();
if (instanceof response !== Error) {
setState("GOOD")
} else {
setState("BAD")
}
}
return { state, fetch }
}
and my test file is something like this:
it("test", async () => {
const { result, waitForNextUpdate } = renderHooks(() => useHook())
await result.current.fetch();
expect(result.current.state).toBe(undefined)
await waitForNextUpdate();
expect(result.current.state).toBe("GOOD") //or at least "BAD"
})
I wrote this because I called the async function fetch()
that should trigger the setState, I assert that no rerender has been occurred yet, and then I waitForNextUpdate()
in order to wait this rerender and I assert that the state
returned by the hooks has now a value "GOOD"
or "BAD"
.
My problem is that my test gives me an error: Timeout - Async callback was not invoked within the 5000 ms ...
, and this error occurred when the test waits for the waitForNextUpdate()
.
I don't know what's wrong with my test. I'm sure (because i tested it) that the hook is working properly, the http call has been made. I know that checking values inside the test but also because the hook is working properly inside the application. I don't understand why it seems that the update of the state never occures.
I'm the first one of my team who is testing with this tool so i'm quite lost.
renderHook
function. However, not all of thoserenderHook
versions return thewaitForNextUpdate
function. – Palladium