Jest mock and typescript

I am writing a test for a function that completes an api fetch.

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

      

And the test for this function looks like this:

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');
});

      

The problem is that typescript doesn't recognize that fetch is mocking, so can't find the mock property on the window. Here is the error:

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

      

How can I fix this?

+3


source to share





All Articles