Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - TypeError: Network request failed for fetch

Tags:

jestjs

fetch

Im using Jest to test a REST API and I'm receiving TypeError: Network request failed responses whenever I issue a fetch request. All of the calls to the REST API work on the application and fail exclusively on my Jest tests.

Are there any known incompatibilities between fetch and Jest? For example this simple test ends up executing the 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 received is: Error!!!!TypeError: Network request failed

like image 343
Joaquín Guillén Melo Avatar asked Oct 19 '16 08:10

Joaquín Guillén Melo


1 Answers

You need to return the Promise that fetch returns:

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 the jest docs about async testing here: https://facebook.github.io/jest/docs/tutorial-async.html

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

import fetch from 'isomorphic-fetch';
like image 105
Lance Fisher Avatar answered Sep 22 '22 09:09

Lance Fisher