1

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);
});
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Aaron
  • 2,364
  • 2
  • 31
  • 56
  • Hope it will help you. https://stackoverflow.com/questions/57196162/how-to-test-async-actions-that-returns-promise – danilovxp Dec 07 '20 at 22:02
  • 2
    The only thing to test _in the provided code_ are the custom Errors. Everything else in this code is simply internal API that has already been tested. So set up _reject_ scenarios and non-400 scenarios. – Randy Casburn Dec 07 '20 at 22:07
  • "*but the result variable is undefined*" - well, it shouldn't be. – Bergi Dec 07 '20 at 22:08
  • Your test double doesn't match the interface it's supposed to be replacing. You could mock more of the fetch API, but for reasons I expand on in https://stackoverflow.com/a/65130857/3001761 it would be better to decouple your code from it. – jonrsharpe Dec 07 '20 at 22:09
  • 1
    that's because the OP is not returning anything from the mock - the mock should return a promise _just like fetch does_. – Randy Casburn Dec 07 '20 at 22:09

0 Answers0