1.1.1 • Published 6 years ago

jest-fetch v1.1.1

Weekly downloads
299
License
Apache-2.0
Repository
gitlab
Last release
6 years ago

Jest Fetch

License Pipelines Coverage NPM

jest-fetch allows you to mock fetch response in jest.

Installation

npm i jest-fetch

Usage

The following examples are based on TypeScript but JavaScript will work fine.

First, you to add setup script. In jest.config.js, add this following configuration.

setupFiles: ["./test/setup.ts"];

setup.ts

import { fetch } from "jest-fetch";

global.fetch = fetch;

You replace the global fetch with jest-fetch. Note that you have to used global fetch in the first place for it to work (e.g. isomorphic-fetch).

example.test.ts

import { mockResponse, resetMocks } from "jest-fetch";

beforeEach(() => {
  resetMocks();
});

test("Test mock string response", async () => {
  const expectResponse = "!!!";
  mockResponse(expectResponse);

  const response = await fetch("https://example.com").then(res => res.text());

  expect(response).toBe(expectResponse);
});

You need to call mockImplementationOnce or mockResponse before your fetch requests. You can pass the response directly or a function.

mockResponse(async (url, init) => {
  return "content";
});

url and init are the variables that you passed to fetch.

Differences from Jest Fetch Mock

jest-fetch-mock does not support you to mock response based URL. This is the reason of this package is created.

1.1.1

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago