Jest Fetch
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
; 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
; beforeEach; test"Test mock string response", ;
You need to call mockImplementationOnce
or mockResponse
before your fetch requests.
You can pass the response directly or a function.
mockResponse;
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.