I'm trying to test a custom hook but for some reason I can't render the hook inside the test closure "it".
This code works (I must use the rerender methods otherwise the result.current.data remains undefined) :
describe('useGet hook', () => {
const { result, rerender, unmount } = renderHook(
() => useGet<IApplication>(getApplication),
{
wrapper: ({ children }) => (
<AuthProvider {...oidcConfig}>{children}</AuthProvider>
),
}
);
it('should make a GET request and return the data', async () => {
rerender()
console.log(result)
});
This code does not work :
it('should make a GET request and return the data', async () => {
const { result, rerender, unmount } = renderHook(
() => useGet<IApplication>(getApplication),
{
wrapper: ({ children }) => (
<AuthProvider {...oidcConfig}>{children}</AuthProvider>
),
}
);
rerender()
console.log(result)
});
In both cases I can see that the loader state has changed (false to true) but the data remains undefined
{
current: {
data: undefined,
error: null,
isLoading: true,
refetch: [Function: executeCallback]
}
}
Here is my customhook :
const useGet = <T,>(
callbackFn: () => Promise<T | null>,
onPersist?: (data: T | null) => void,
onError?: (error: ConnectError | null) => void
): useGetResponseType<T> => {
const [data, setData] = useState<T | null>();
const [error, setError] = useState<ConnectError | null>(null);
const [isLoading, setIsLoading] = useState(false);
const { userData } = useAuth();
const executeCallback = () => {
if (!callbackFn) {
return Promise.resolve(null);
}
setIsLoading(true);
return callbackFn()
.then((dataResponse: T | null) => {
setData(dataResponse);
if (onPersist) {
onPersist(dataResponse);
}
return dataResponse;
})
.catch((errorResponse: AxiosError<ConnectError>) => {
setError(errorResponse?.response?.data || null);
if (onError) {
onError(errorResponse?.response?.data || null);
}
return null;
})
.finally(() => {
setIsLoading(false);
});
};
useEffect(() => {
if (isLoading || !userData) {
return;
}
executeCallback();
}, [userData]);
return {
data,
error,
isLoading,
refetch: executeCallback,
};
};