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

J T picture J T · Mar 17, 2016 · Viewed 36.9k times · Source

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?

Answer

Alexey Kureev picture Alexey Kureev · Mar 17, 2016

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).