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
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With