I have a query regarding the following code snippet:
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);
});
Upon removing as Response
, I am encountering a 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 am seeking guidance on how to effectively mock the fetch
without using as Response
as it seems like an unfavorable practice.