Skip to content

Instantly share code, notes, and snippets.

@Chester97
Last active January 10, 2021 16:18
Show Gist options
  • Save Chester97/86f8dea06e05f0bfc4e23481fa445802 to your computer and use it in GitHub Desktop.
Save Chester97/86f8dea06e05f0bfc4e23481fa445802 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react';
export default function useFetch(apiUrl) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const getData = async (url) => {
setLoading(true);
try {
const response = await fetch(url);
const data = await response.json();
setData(data);
return data;
} catch(e) {
setError(e);
return e;
} finally {
setLoading(false);
return;
}
}
getData(apiUrl);
}, [apiUrl]);
return {data, loading, error};
};
import { renderHook } from '@testing-library/react-hooks'
import useFetch from './useFetch';
const DATA_MOCK = {
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
};
describe('useFetch', () => {
// beforeAll(() => {
// global.fetch = jest.fn().mockReturnValue(Promise.resolve({
// json: () => Promise.resolve({
// "userId": 1,
// "id": 1,
// "title": "delectus aut autem",
// "completed": false
// })
// }))
// });
// afterAll(() => {
// global.fetch.mockClear();
// });
test('should return data', async () => {
global.fetch = jest.fn().mockReturnValue(Promise.resolve({
json: () => Promise.resolve({
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
})
}))
const { result, waitForNextUpdate } = renderHook(() => useFetch('https://jsonplaceholder.typicode.com/todos/1'));
await waitForNextUpdate();
console.log(result.current);
// console.log
// {
// data: null,
// loading: false,
// error: TypeError: Cannot read property 'json' of undefined
// at getData (/random-components-practice/src/hooks/useFetch/useFetch.js:13:37)
// }
// expect(result.current.data).toBeTruthy(); // problem
expect(result.current.data).toMatchObject(DATA_MOCK);
expect(result.current.loading).toBeFalsy();
expect(result.current.error).toBeNull();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment