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?
As @ArthurDenture recommended, you can use fetch-mock, but there are some additional packages you will need to install to make it work with React Native and Jest:
You can then mock fetch requests in your tests. Here is an example:
Another approach where you mock the global
fetch
object:The above helper method can be modified any way you want :-) Hope it helps someone
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.
Inside your test case you can mock any function you want by using Jest's mocks:
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 usingpit
(read more about async tests here).As shown in the react-testing-library documentation, you can use the jest.spyOn() function, which will mock the fetch function only for the next time it is called.
react-testing-library
Suppose you want to test resolve and reject cases, for this first you mock the fetch behaviour and then use Jest's rejects and resolves methods with with assertion block