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)
小智 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 是我需要返回的对象,您可以将其替换为您必须返回的对象或基元。
你也可以使用这个,它类似于这个答案/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 简单获取模拟
| 归档时间: |
|
| 查看次数: |
39841 次 |
| 最近记录: |