Typescript 笑话和打字稿

Typescript 笑话和打字稿,typescript,jestjs,Typescript,Jestjs,我正在为封装fetchapi的函数编写测试 const callAPI = (uri: string, options: RequestParams) => { let headers = { requestId: shortid.generate() }; if (options.headers) { headers = { ...options.headers, ...headers}; } const opts = {...opt

我正在为封装fetchapi的函数编写测试

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');
});
问题是typescript无法识别fetch是模拟的,因此无法在window.fetch上找到mock属性 以下是错误:

[ts] Property 'mock' does not exist on type '(input: RequestInfo, init?: RequestInit) => Promise<Response>'.
[ts]属性“mock”在类型“(输入:RequestInfo,init?:RequestInit)=>Promise”上不存在。

如何修复此问题?

您需要将
窗口.fetch
重新定义为
jest.Mock
。为了清晰起见,最好定义一个不同的变量:

it('should add requestId to headers', () => {
    const fakeFetch = jest.fn();
    window.fetch = fakeFetch;
    callAPI('localhost', { method: 'POST' });
    expect(fakeFetch.mock.calls[0][1]).toHaveProperty('headers');
    expect(fakeFetch.mock.calls[0][1].headers).toHaveProperty('requestId');
});

也可考虑移动<代码>窗口的嘲讽。在测试之外取出.<代码>以恢复它。

<代码>它('Test.',dot= >{
it('test.', done => {
    const mockSuccessResponse = {YOUR_RESPONSE};
    const mockJsonPromise = Promise.resolve(mockSuccessResponse);
    const mockFetchPromise = Promise.resolve({
        json: () => mockJsonPromise,
    });
    var globalRef:any =global;
    globalRef.fetch = jest.fn().mockImplementation(() => mockFetchPromise);

    const wrapper = mount(
          <MyPage />,
    );

    done();

  });
const mockSuccessResponse={YOUR_RESPONSE}; const mockJsonPromise=Promise.resolve(mockSuccessResponse); const mockFetchPromise=Promise.resolve({ json:()=>mockJsonPromise, }); var globalRef:any=全局; globalRef.fetch=jest.fn().mockImplementation(()=>mockFetchPromise); 常量包装器=装入( , ); 完成(); });
您正在使用ts jest吗?
声明let global:{fetch:{}
并使用
global.fetch()
而不是
window.fetch()