Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test API calls with mocked fetch() in react-native with Jest

In React Native I use fetch to perform network requests, however fetch is not an explicitly required module, so it is seemingly impossible to mock in Jest.

Even trying to call a method which uses fetch in a test will result in:

ReferenceError: fetch is not defined

Is there a way to test such API requests in react native with Jest?

like image 511
J T Avatar asked Mar 17 '16 19:03

J T


People also ask

How do you mock fetch response in Jest?

Manual Mock One option when manually mocking a module is to create a folder named __mocks__ and place a file in it with the same name as the module you are mocking. In our case we can do this, and that is because fetch is available globally. So instead we will override the global.


4 Answers

Inside your test case you can mock any function you want by using Jest's mocks:

fetch = jest.fn(() => Promise.resolve());

This approach works only for the promise-based test cases (see pit in the Jest docs).

As far as fetch is an async function, you need to run all your tests using pit (read more about async tests here).

like image 169
Alexey Kureev Avatar answered Oct 23 '22 21:10

Alexey Kureev


Another approach where you mock the global fetch object:

const mockSuccesfulResponse = (
  status = 200,
  method = RequestType.GET,
  returnBody?: object
) => {
  global.fetch = jest.fn().mockImplementationOnce(() => {
    return new Promise((resolve, reject) => {
      resolve({
        ok: true,
        status,
        json: () => {
          return returnBody ? returnBody : {};
        },
      });
    });
  });
};

The above helper method can be modified any way you want :-) Hope it helps someone

like image 36
jhm Avatar answered Oct 23 '22 19:10

jhm


Rather than rolling your own mock, you can use the jest-fetch-mock npm package to override the global fetch object. That package allows you to set up fake responses and verify sent requests. See that link for extensive usage examples.

like image 7
ArthurDenture Avatar answered Oct 23 '22 21:10

ArthurDenture


I solved this by adding isomorphic-fetch.

$ npm install --save isomorphic-fetch

and using it like

import fetch from 'isomorphic-fetch';
...
fetch('http://foo.com');

whatwg-fetch might work as well

like image 2
Harry Moreno Avatar answered Oct 23 '22 19:10

Harry Moreno