繁体   English   中英

在 Typescript 中获取的正确模拟

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM