Proper mock of fetch in Typescript

Viewed 3091

I've got a question about this code:

import useCountry from './useCountry';
import { renderHook } from '@testing-library/react-hooks';
import { enableFetchMocks } from 'jest-fetch-mock';
enableFetchMocks();

it('should make proper api call', async () => {
  const resultCountries = {
    PL: 'Poland',
    CA: 'Canada',
  };

  jest.spyOn(global, 'fetch').mockImplementation(() =>
    Promise.resolve({
      json: () => Promise.resolve(resultCountries),
    } as Response),
  );

  const expected = [
    { code: 'PL', name: 'Poland' },
    { code: 'CA', name: 'Canada' },
  ];

  const { result, waitForNextUpdate } = renderHook(() => useCountry());
  await waitForNextUpdate();

  expect(fetch).toHaveBeenCalled();
  expect(result.current).toEqual(expected);
});

When removing as Response, I'm getting this Typescript warning:

TS2345: Argument of type '() => Promise<{ json: () => Promise<{ PL: string; CA: string; }>; }>' is not assignable to parameter of type '(input?: string | Request | undefined, init?: RequestInit | undefined) => Promise'.   Type 'Promise<{ json: () => Promise<{ PL: string; CA: string; }>; }>' is not assignable to type 'Promise'.     Type '{ json: () => Promise<{ PL: string; CA: string; }>; }' is missing the following properties from type 'Response': headers, ok, redirected, status, and 11 more.

I would like to ask how to properly mock the fetch, because this as Response feels like a bad practise.

0 Answers
Related