Skip to content
Latchkey

Jest "ReferenceError: document is not defined" (node env) in CI

The test ran under the node test environment, which has no DOM. Browser globals such as document and window are undefined there, so any code that touches them throws a ReferenceError.

What this error means

A component or DOM test fails with "ReferenceError: document is not defined" (or window is not defined). It often follows upgrading to Jest 28+, where jsdom stopped being the default environment.

Jest output
ReferenceError: document is not defined

      4 | export function mount() {
    > 5 |   const root = document.getElementById('root');
        |                ^
      6 |   render(<App />, root);

Common causes

The node environment has no DOM

Jest 28 and later default testEnvironment to node, which provides no document/window, so DOM-dependent code fails.

jsdom is not selected for DOM tests

The project upgraded Jest but never set testEnvironment: "jsdom" (or the per-file docblock), so browser tests run in node.

How to fix it

Select the jsdom environment

  1. Install jest-environment-jsdom (it is a separate package since Jest 28).
  2. Set testEnvironment: "jsdom" globally, or per file with a docblock.
  3. Re-run so DOM globals are available.
jest.config.js
// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
};

Or opt in per file

For a mixed suite, set the environment with a docblock at the top of DOM test files only.

src/dom.test.js
/**
 * @jest-environment jsdom
 */

How to prevent it

  • Set testEnvironment explicitly so it does not depend on the Jest default.
  • Install jest-environment-jsdom when you rely on it (Jest 28+).
  • Use docblocks to scope jsdom to the tests that need it.

Frequently asked questions

What causes ""ReferenceError: document is not defined""?
Jest 28 and later default testEnvironment to node, which provides no document/window, so DOM-dependent code fails.
How do I fix "ReferenceError: document is not defined"?
Select the jsdom environment

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card