12

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?

2
  • Are you using ts-jest? Commented Jun 28, 2017 at 1:53
  • 3
    declare let global: { fetch: {} }; and use global.fetch() not window.fetch(). Commented Aug 30, 2017 at 22:02

2 Answers 2

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

  });
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.