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);
});
});