开玩笑的模拟和打字稿

Nic*_*ick 6 typescript jestjs

我正在为包装提取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);
};
Run Code Online (Sandbox Code Playgroud)

并对此功能进行如下测试:

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');
});
Run Code Online (Sandbox Code Playgroud)

问题是打字稿无法识别提取是模拟的,因此无法在window.fetch上找到模拟属性。这是错误:

[ts] Property 'mock' does not exist on type '(input: RequestInfo, init?: RequestInit) => Promise<Response>'.
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

mes*_*kin 8

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();

  });
Run Code Online (Sandbox Code Playgroud)


小智 4

您需要重新定义window.fetchjest.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');
});
Run Code Online (Sandbox Code Playgroud)

还可以考虑将mocking移到window.fetch测试之外以在事后恢复。