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.
I had this problem with mocking fetch
function and just add the below code in .test.tsx
.
//app.test.tsx
global.fetch = jest.fn(async () =>
Promise.resolve({ json: async () => Promise.resolve({ id: 0 }) })
) as jest.Mock;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.