Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest mock and typescript

i am writing a test for a function that wraps the 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);
};

And the test for this function 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 does not recognize that fetch is mocked thus can not find mock property on window.fetch Here is the error:

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

How could i fix this?

like image 543
Nick Avatar asked May 25 '17 12:05

Nick


Video Answer


2 Answers

You need to redefine window.fetch as a jest.Mock. For clarity it's better to define a different variable:

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

Also consider moving the mocking of window.fetch outside the test to restore it afterwards.

like image 34
Andres Martinez Avatar answered Oct 21 '22 08:10

Andres Martinez


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

  });
like image 129
mesutpiskin Avatar answered Oct 21 '22 09:10

mesutpiskin