使用 Typescript 和 Jest 进行简单的 fetch mock [英] Simple fetch mock using Typescript and Jest
本文介绍了使用 Typescript 和 Jest 进行简单的 fetch mock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
What would be my absolute easiest way of mocking fetch using Typescript?
I would just like to do something simple like below. But Typescript tells me that I'm not matching the definition for the full fetch object.
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.
What would be the simplest solution to get around this? Actually mock out the whole fetch object or other solution?
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ test: 100 }),
}),
)
解决方案
You can tell TypeScript that you're defining global.fetch
as a Jest mock.
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ test: 100 }),
}),
) as jest.Mock;
这篇关于使用 Typescript 和 Jest 进行简单的 fetch mock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文