unmock-fetch
TypeScript icon, indicating that this package has built-in type declarations

0.3.18 • Public • Published

unmock-fetch

npm CircleCI codecov Known Vulnerabilities

Interceptor and faker for fetch.

Installation

npm i -D unmock-fetch
yarn add unmock-fetch -D

Usage

Usage as fake fetch

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

Readme

Keywords

none

Package Sidebar

Install

npm i unmock-fetch

Weekly Downloads

133

Version

0.3.18

License

MIT

Unpacked Size

163 kB

Total Files

22

Last publish

Collaborators

  • meeshkan