Fix Jest error "ReferenceError: Request is not defined"


Problem

If you get the Jest error:

ReferenceError: Request is not defined

This is due to jsdom not supporting fetch (see #1724).

Solution 1

One approach is to install whatwg-fetch:

npm install --save-dev whatwg-fetch

And polyfill it in one of Jest’s setupFiles like setupTests.js:

import 'whatwg-fetch';

Alternatively, you can install isomorphic-fetch:

npm install --save-dev isomorphic-fetch

And polyfill it in one of Jest’s setupFiles like setupTests.js:

import 'isomorphic-fetch';

Solution 2

If you plan to mock fetch, you can install jest-fetch-mock:

npm install --save-dev jest-fetch-mock

Then enable it one of Jest’s setupFiles like setupTests.js:

require('jest-fetch-mock').enableMocks();


Please support this site and join our Discord!