【发布时间】:2020-02-24 21:03:42
【问题描述】:
我正在为包装 fetch api 的函数编写测试。
const callAPI = (uri: string, options: RequestParams) => {
let headers = { requestId: shortid.generate() };
if (options.headers) {
headers = { ...options.headers, ...headers};
}
const opts = {...options, ...{ headers }};
return fetch(uri, opts);
};
这个函数的测试是这样的:
it('should add requestId to headers', () => {
window.fetch = jest.fn();
callAPI('localhost', { method: 'POST' });
expect(window.fetch.mock.calls[0][1]).toHaveProperty('headers');
expect(window.fetch.mock.calls[0][1].headers).toHaveProperty('requestId');
});
问题是打字稿无法识别 fetch 被模拟,因此无法在 window.fetch 上找到模拟属性 这是错误:
[ts] Property 'mock' does not exist on type '(input: RequestInfo, init?: RequestInit) => Promise<Response>'.
我该如何解决这个问题?
【问题讨论】:
-
你在用 ts-jest 吗?
-
declare let global: { fetch: {} };并使用global.fetch()而不是window.fetch()。
标签: typescript jestjs