【发布时间】:2021-12-03 09:01:27
【问题描述】:
我是打字稿的新手,如果这是微不足道的,请提前道歉。 我有一个像这样在内部使用 Fetch 的函数
export class MyClass {
classVar1: string;
classVar2: string;
...
async postEvent(event: eventSchema) {
const headers = {
'Content-type': 'application/json',
'Api-Key': 'APIKEY}',
};
let result = null;
const response = await fetch('url', {
method: 'POST',
body: event,
headers: headers,
});
result = await response;
return result;
}
}
我正在尝试测试 postEvent 方法,为此我正在尝试仅模拟 fetch 部分。 但无论我如何处理这个问题,实际方法仍然是被调用的方法。 根据我在网上找到的内容,这就是我的 .spec.ts 文件中的内容
import { MyClass } from './my-class';
import fetch from 'node-fetch';
jest.mock('node-fetch');
describe('My class mocked fetch', () => {
beforeEach(() => {
(MyClass as any).postEvent = jest.fn();
(fetch as any) = jest.fn().mockResolvedValue({
url: 'url',
status: 200,
statusText: 'OK',
counter: 0,
});
});
it('Calls mockedFetch and gets the mocked values', async () => {
expect(fetch).toHaveBeenCalledTimes(0);
const response = await myClass.postEvent('testMsg')
console.log('RESPONSE', response)
});
在最后一行 (console.log('RESPONSE', response)),我希望看到 mockResolved 值,即
url: 'url',
status: 200,
statusText: 'OK',
counter: 0,
但它会返回实际 fetch 会生成的任何内容。
有人可以帮忙吗?
p.s 我还阅读了有关 spyOn 方法的信息,但我无法找到适合我上面用例的打字稿示例。 JS有这样的例子
const fetchMock = jest.spyOn(global, 'fetch').mockImplementation(() => Promise.resolve({ json: () => Promise.resolve([]) }))
但是如果在下面的类型脚本中使用它会引发异常
'Promise<{ json: () => Promise<any[]>; }>' is not assignable to type 'Promise<Response>'.
【问题讨论】:
标签: typescript jestjs mocking fetch