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

1.1.1 • Public • Published

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.

Readme

Keywords

Package Sidebar

Install

npm i jest-fetch

Weekly Downloads

43

Version

1.1.1

License

Apache-2.0

Unpacked Size

33.9 kB

Total Files

10

Last publish

Collaborators

  • joshuaavalon