unmock-fetch
v0.3.18
Published
[](https://www.npmjs.com/package/unmock-fetch) [](https://circleci.com/gh/unmock/unmock-js) [: ISerializedResponse => {
return {
headers: {},
statusCode: 200,
body: JSON.stringify({
ok: true,
}),
};
};
// Build `fetch` with your callback
const fetch = buildFetch(responseCreator);
// Make API calls!
const response = await fetch("https://example.com");
const asJson = await response.json();
expect(asJson.ok).toBe(true);Usage as interceptor
To override global.fetch or window.fetch, use the default import:
import FetchInterceptor from "unmock-fetch";
// What to do with serialized request
const requestCb: (
req: ISerializedRequest
) => ISerializedResponse = /* as above */
// Intercept `global.fetch` or `window.fetch`
FetchInterceptor.on(requestCb);
// Make API calls
const response = await fetch("https://example.com");
const asJson = await response.json();
expect(asJson.ok).toBe(true);
// Stop interceptor, restoring `global.fetch` or `window.fetch`
FetchInterceptor.off();