简体   繁体   English

在 Typescript 中获取的正确模拟

[英]Proper mock of fetch in Typescript

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: as Response删除时,我收到此 Typescript 警告:

TS2345: Argument of type '() => Promise<{ json: () => Promise<{ PL: string; TS2345: '() => Promise<{ json: () => Promise<{ PL: string; 类型的参数CA: string; CA:字符串; }>; }>; }>' is not assignable to parameter of type '(input?: string | Request | undefined, init?: RequestInit | undefined) => Promise'. }>' 不可分配给类型为'(input?: string | Request | undefined, init?: RequestInit | undefined) => Promise' 的参数。 Type 'Promise<{ json: () => Promise<{ PL: string;输入'Promise<{ json: () => Promise<{ PL: string; CA: string; CA:字符串; }>; }>; }>' is not assignable to type 'Promise'. }>' 不可分配给类型 'Promise'。 Type '{ json: () => Promise<{ PL: string;输入'{ json: () => Promise<{ PL: string; CA: string; CA:字符串; }>; }>; }' is missing the following properties from type 'Response': headers, ok, redirected, status, and 11 more. }' 缺少类型 'Response' 中的以下属性:headers、ok、redirected、status 等 11 个。

I would like to ask how to properly mock the fetch , because this as Response feels like a bad practise.我想问一下如何正确模拟fetch ,因为这as Response感觉像是一种不好的做法。

I had this problem with mocking fetch function and just add the below code in .test.tsx .我在 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