Jest - TypeError: network request failed to retrieve

I use Jest to test the REST API, and I get a TypeError: requests with network failures are requested whenever I issue a fetch request. All REST API calls work on the application and fail solely on my Jest tests.

Are there any known incompatibilities between fetch and Jest? For example, this simple test ends with a catch statement:

it('should find a result via fetch', () => { fetch('http://www.google.com').then(() => console.log('Success')).catch((err) => console.log('Error!!!!' + err)); }); 

The result: Error !!!! TypeError: network request failed

+6
source share
2 answers

You need to return a Promise that returns fetch :

 it('should find a result via fetch', () => { return fetch('http://www.google.com') .then(() => console.log('Success')) .catch((err) => console.log('Error!!!!' + err)); }); 

You can read more in jest docs on asynchronous testing here: https://facebook.imtqy.com/jest/docs/tutorial-async.html

Also, using jest in create-react-app will use whatwg-fetch polyfill through jsdom. You can force the use of isomorphic-fetch by importing it directly:

 import fetch from 'isomorphic-fetch'; 
+4
source

Ok, I got this to work using async, but I still don't understand why it doesn't work without the async block. So now my test works with this code:

 it('should find a result via REST', async () => { const data = await CqApi.personSearch('XYZ'); expect(....).toBeDefined(); }); 
0
source

Source: https://habr.com/ru/post/1011468/


All Articles