Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Jest tests cannot use fetch even though Node.js has it built in

ErrorReferenceError: fetch is not defined

Short answer

Node.js has had a global fetch since version 18, but Jest runs each test inside its own environment. The jsdom environment does not offer fetch, and Jest maintainers say fetch is available only in the node environment. Run API tests in the node environment, give DOM tests their own fetch mock, and make sure Node is 18 or newer.

  • Applies to Jest (current docs), Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Check the Node.js version and which test environment Jest uses. The environment is set in the Jest config or at the top of the test file.

    node --version
    grep -rn "testEnvironment\|@jest-environment" jest.config.* package.json src
  2. 2Match what you see, then jump to its fix

    1. 1The test calls your API client or a server helper, and the config says testEnvironment: 'jsdom'The project sets testEnvironment to jsdom, and the failing test does not need a DOMFix
    2. 2The test renders a component, and the error is thrown from the component's data loadingA component test needs jsdom and also calls fetchFix
    3. 3The same tests pass on your machine but fail in CI, and the CI image has an older Node.jsNode.js is older than 18Fix

What does the error look like?

  • ReferenceError: fetch is not defined

Cause 1 of 3

The project sets testEnvironment to jsdom, and the failing test does not need a DOM

1Check

Jest's default environment is node. A web project often switches the whole run to jsdom, a browser-like environment. A Jest project member answered the fetch report by saying that fetch is available in the node environment, and the jsdom project's own tracker still has an open request to implement the Fetch API.

grep -rn "testEnvironment" jest.config.* package.json

2Fix

Put the node environment on the files that do not touch the DOM, with a docblock at the top of each one.

/**
 * @jest-environment node
 */
test('loads data', async () => {
  const res = await fetch('http://localhost:3000/health');
  expect(res.ok).toBe(true);
});

3Verify

Run that test file alone; fetch is found.

npx jest path/to/api.test.js

Confirmed by jestjs.io

Did this fix it?

Cause 2 of 3

A component test needs jsdom and also calls fetch

1Check

In this case the test must stay in jsdom, where fetch does not exist.

grep -rn "fetch(" src --include=*.js --include=*.jsx --include=*.ts --include=*.tsx

2Fix

Give the test its own fetch in a setup file that Jest runs after the framework is installed, and shape the response the component reads.

// jest.setup.js
global.fetch = jest.fn(() =>
  Promise.resolve({
    ok: true,
    json: () => Promise.resolve({ items: [] }),
  })
);

// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};

3Verify

Run the component's tests; the ReferenceError is gone and the component renders with the mocked data.

npx jest src/components

Confirmed by jestjs.io

Did this fix it?

Cause 3 of 3

Node.js is older than 18

1Check

Node.js documents fetch as added in v17.5.0 and v16.15.0 behind an experimental flag, no longer behind the flag from v18.0.0, and stable from v21.0.0.

node --version

2Fix

Use a current Node.js release in CI and locally, and pin it in the project.

# .nvmrc
22

3Verify

node --version prints a v22 line and the tests run.

node --version && npx jest

Confirmed by nodejs.org

Did this fix it?

How do I stop it coming back?

  • Decide per test file which environment it needs. Keep the default node, and opt in to jsdom for tests that render components.
  • Pin the Node.js version in .nvmrc or the engines field so CI and laptops agree.
  • Mock network calls at one shared setup point, so each component test does not invent its own fetch.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.