I have never had to test a function like this before. Any ideas would be appreciated. The function basically passes a url to fetch and returns json. The url tells fetch which static json file to get.
const getJSON = async <T>(url): Promise<T> => {
try {
return await fetch(url).then(res => {
if (!res.ok) {
throw new Error('Network response was not ok.');
}
if (!res.headers.get('content-type').includes('application/json')) {
throw new Error('Response is not JSON');
}
return res.json();
});
} catch (e) {
// some error handling
}
};
export default fetchJSON;
At first glance I don't even know what to test. The only thing I came up with was to try and spy on the fetch method and force the response to be a some mocked data. I tried the following. I tried to mock fetch and call it. The expect seen below passes but the result variable is undefined so I can't test any return value.
import fetchJSON from '../fetchJSON';
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ name: 'foo' }),
})
);
beforeEach(() => {
fetch.mockClear();
});
it('finds blah blah', async () => {
const result = await fetchJSON('');
expect(fetch).toHaveBeenCalledTimes(1);
});