Reputation: 171
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
Upvotes: 17
Views: 17350
Reputation: 25813
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';
Upvotes: 8
Reputation: 171
Ok I've gotten this to work using async await, but I still don't understand why it doesn't work without an async block- So right now my test works with this code:
it('should find a result via REST', async () => {
const data = await CqApi.personSearch('XYZ');
expect(....).toBeDefined();
});
Upvotes: 0