使用 Typescript 和 Jest 进行简单的获取模拟

Rir*_*iri 37 fetch typescript jestjs

使用 Typescript 模拟 fetch 的最简单方法是什么?

我只想做一些简单的事情,如下所示。但 Typescript 告诉我,我与完整获取对象的定义不匹配。

Type 'Mock<Promise<{ json: () => Promise<{ test: number; }>; }>, []>' is not assignable to type '(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>'.
   Type 'Promise<{ json: () => Promise<{ test: number; }>; }>' is not assignable to type 'Promise<Response>'.
     Type '{ json: () => Promise<{ test: number; }>; }' is missing the following properties from type 'Response': headers, ok, redirected, status, and 11 more.
Run Code Online (Sandbox Code Playgroud)

解决这个问题最简单的解决方案是什么?实际上模拟了整个获取对象或其他解决方案?

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ test: 100 }),
  }),
)
Run Code Online (Sandbox Code Playgroud)

our*_*dam 102

您可以告诉 TypeScript 您正在定义global.fetch为 Jest 模拟。

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ test: 100 }),
  }),
) as jest.Mock;
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用它,它是类似的: jest.spyOn(global, "fetch").mockImplementation( jest.fn(() =&gt; Promise.resolve({ json: () =&gt; Promise.resolve({ data: 100 }), }), ) 作为笑话.Mock ) (17认同)
  • 伙计,我浪费了两天时间,谢谢... (4认同)
  • @GreatQuestion我觉得你的使用spyOn是一个更好的实现。我不知道为什么,但使用间谍On比简单地使用jest.fn()产生的未定义错误要少得多。如果您将其作为单独的答案发布,那就更好了。 (2认同)

小智 10

我在使用之前的方法时遇到了一些问题,以下是我的解决方法:

首先是我的测试代码:

describe("Testing the Assets Service", () => {
let fetchMock: any = undefined;

beforeEach(() => {
    fetchMock = jest.spyOn(global, "fetch")
    .mockImplementation(assetsFetchMock);
});

afterEach(() => {
    jest.restoreAllMocks();
});

test('Fetch has been called', () => {
    const baseUrl = "https://myurl.com"
    fetchAssets(baseUrl);
    expect(fetchMock).toHaveBeenCalled();
    expect(fetchMock).toHaveBeenCalledWith(baseUrl);
}); 
});
Run Code Online (Sandbox Code Playgroud)

函数 fetchAssets 使用特定的 url 调用 fetch 函数。

现在是模拟获取行为的函数:

export const assetsFetchMock = () => Promise.resolve({
ok: true,
status: 200,
json: async () => clientAssets
} as Response);
Run Code Online (Sandbox Code Playgroud)

clientAssets 是我需要返回的对象,您可以将其替换为您必须返回的对象或基元。


mew*_*ewc 8

你也可以使用这个,它类似于这个答案/sf/answers/4537368181/

jest.spyOn(global, "fetch").mockImplementation( 
  jest.fn(
    () => Promise.resolve({ json: () => Promise.resolve({ data: 100 }), 
  }), 
) as jest.Mock ) 
Run Code Online (Sandbox Code Playgroud)

来自此评论使用 Typescript 和 Jest 简单获取模拟