unmock-fetch
Interceptor and faker for fetch.
Installation
npm i -D unmock-fetch
yarn add unmock-fetch -D
Usage
fetch
Usage as fake import { buildFetch } from "unmock-fetch";
import { ISerializedRequest, ISerializedResponse, OnSerializedRequest } from "unmock-core";
// Define what to do with the intercepted request
const responseCreator = (
req: ISerializedRequest
): 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();