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?
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With