Im learning react testing and i have this hook i want to test but i have no idea how
import { useState, useCallback } from 'react';
import axios from 'axios';
export const useFetch = () => {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const fetchData = useCallback(async (url: string) => {
setLoading(true);
try {
const response = await axios.get(url);
const data = await response.data.data;
setLoading(false);
return data;
} catch (error: any) {
if (error.name !== 'AbortError') {
setLoading(false);
setError(error.message);
}
}
}, []);
return { error, loading, fetchData };
};
what i got so far but this is just me trying stuff cuzz there is no much help online that is good for my case
import { useFetch } from '../../hooks/useFetch';
import mockAxios from 'jest-mock-axios';
import axios from 'axios';
import { renderHook } from '@testing-library/react-hooks';
jest.mock('axios');
describe('useFetch', () => {
afterEach(() => {
mockAxios.reset();
});
it('fetches successfully data from an API', async () => {
const { result,waitFor } = renderHook(() => useFetch());
let responseObj = { data: 'test response' };
mockAxios.mockResponseFor({ url: '/get' }, responseObj);
expect(result.current.error).toBe(null);
await expect(result.current.fetchData('react')).resolves.toBe(responseObj);
});
});
When you try to call
setStatemutate the state. We need to use act() function toSince your
fetchDatareturns a promise, we need to useasync act(...), you need React version at leastv16.9.0-alpha.0. For more info aboutact()function, see react-act-example.react-hook-testing-libraryre-export act() function from chosen renderer.Besides, I just use
jest.spyOn(axios, 'get').mockResolvedValueOnce()to mockaxios.get()method without installing any extra package.Note: I return
response.data, notawait response.data.data.Now, the working unit test should be:
useFetch.ts:useFetch.test.ts:Test result:
package versions: