[英]TypeError: Fetch failed in SvelteKit server-side rendering - Express does not show a proper TypeScript stack trace
[英]Proper mock of fetch in Typescript
我對這段代碼有疑問:
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);
});
as Response
刪除時,我收到此 Typescript 警告:
TS2345: '() => Promise<{ json: () => Promise<{ PL: string; 類型的參數 CA:字符串; }>; }>' 不可分配給類型為'(input?: string | Request | undefined, init?: RequestInit | undefined) => Promise' 的參數。 輸入'Promise<{ json: () => Promise<{ PL: string; CA:字符串; }>; }>' 不可分配給類型 'Promise'。 輸入'{ json: () => Promise<{ PL: string; CA:字符串; }>; }' 缺少類型 'Response' 中的以下屬性:headers、ok、redirected、status 等 11 個。
我想問一下如何正確模擬fetch
,因為這as Response
感覺像是一種不好的做法。
我在 mocking fetch
function 時遇到了這個問題,只需在.test.tsx
中添加以下代碼。
//app.test.tsx
global.fetch = jest.fn(async () =>
Promise.resolve({ json: async () => Promise.resolve({ id: 0 }) })
) as jest.Mock;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.