Nock on Node 18/20/22 Fails to Intercept isomorphic-unfetch/fetch Request
On Node versions 18, 20 and 22, users may encounter an issue where Nock fails to intercept requests made via isomorphic-unfetch.
What follows is a sample error you may see (timeout is reached because the request is not intercepted).
returns a valid response
thrown: "Exceeded timeout of 5000 ms for a test.
Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."
1 |
> 2 | it('returns a valid response', async () => {
Table of Contents
Why does this happen?
The issue arises because Node 18+ supplies a global.fetch
. In systems that use isomorphic-unfetch
, the global.fetch
instance is used if available, which causes the problem. Consumers that explicitly use node-fetch
or cross-fetch
(which relies on node-fetch
) are not affected.
See the relevant source file in isomorphic-unfetch repository: packages/isomorphic-unfetch/index.js
Relevant GitHub issues discussing this problem include:
How to Fix?
There are a few short-term approaches to resolve this issue:
One option is to override global.fetch
with node-fetch
. This can be done by placing the following code in a jest.setup.ts
file (or the equivalent Jest/test runner setup file):
// nock doesn't support native fetch, and hence we need this patch.
import fetch, { Headers, Request, Response } from 'node-fetch';
(global as any).fetch = fetch;
(global as any).Headers = Headers;
(global as any).Request = Request;
(global as any).Response = Response;
Refer to this GitHub comment for more details.
Another option is to set NODE_OPTIONS="--no-experimental-fetch"
in your test running command. For example:
"scripts": {
"test": "NODE_OPTIONS='--no-experimental-fetch' jest"
}
This will disable the native fetch, causing isomorphic-unfetch
to use node-fetch
, (see Node.js docs).
For a more long-term solution, consider migrating to undici
’s MockAgent().get().intercept()
or using the msw (mock service worker) package, which supports fetch through its own patching. See the following links:
Get The Jest Handbook (100 pages)
Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.
orJoin 1000s of developers learning about Enterprise-grade Node.js & JavaScript