Despite mocking custom hook, when rendering App component that uses this hook I still get data from call to original api and alsot test gives this error:
Matcher error: received value must be a mock or spy function
Received has value: undefined
Why is the hook not mocked?
test('renders table when data is loaded', async () => {
jest.mock('./hooks/useFetch', () => ({
__esModule: true,
default: () => {
const original = jest.requireActual('./hooks/useFetch');
return {
...original,
fetchData: jest.fn()
}
}
}));
const mockFetchData = jest.fn().mockImplementation((data) => {
global.fetch = jest.fn().mockResolvedValueOnce(data);
});
const mockData = [
{ id: 1, title: 'Type 1' },
{ id: 2, title: 'Type 2' },
];
render(<App />);
await waitFor(() => expect(mockFetchData(mockData)).toHaveBeenCalledTimes(1))
});
Custom hook looks like this:
const useFetch = () => {
const fetchData = useCallback( async (url, callback) => {
try {
const response = await fetch(url)
const data = await response.json();
callback(data)
} catch (error) {
setError(error.message || 'An error occurred')
}
},[]);
return { fetchData }
};
export default useFetch;
Callback in this hook is a function from App which sets state of data (setData)
I tried implementing answer from here: Can't mock useAsync with react test library but with no success.