Node.js document is not defined

You could use JSDom to add Dom support to Node. To make a variable global you can use either

GLOBAL.document = new JSDOM(html).window.document;

or

global.document = new JSDOM(html).window.document;

where html is your website as a string.

To use JSDom include it in your project with:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;

or in plain js with:

var jsdom = require("jsdom");
var JSDOM = jsdom.JSDOM;

I hope this is answering your question.


From the docs just add this comment to the top of your .test.js file to configure your environment:

/**
* @jest-environment jsdom
*/

To understand the answer, it's necessary to know the relationship of: Javascript Engine, Browser and Node.js.

Javascript Engine: is Javascript compiler which turns JS into machine code. For example, V8, is a great one. Technically V8 is developed in C++ (you can regard it as a C++ program).

V8 implements ECMAScript, which is a standard of Javascript language defining the features and functionalities of JavaScript.

But DOM operation is not defined by ECMAScript. So V8 doesn't support it.

Browser: And developers can use document for DOM operation in browser, because DOM operation is provided by browser, for example: Chrome.

Chrome is also developed by C++ and V8(as mentioned abvoe, which is developed by C++ as well) is embedded into Chrome to interpret Javascript. So Chrome expends or adds features to Javascript by binding JS command and C++ implementation together.

Nodejs: different from the Chrome, it is a server side program. But the same thing is that Nodejs is developed by C++ and V8 is embedded into Nodejs to handle js. Nodejs expands features of Javascript in the similar way with Chrome. But since server side doesn't need to handle DOM, so you can not access such functions inside Nodejs.


document relates to the DOM (Document Object Model) in a web browser.

Node.js, however, is not a browser environment. It is a server environment, much like PHP or Perl, and as such, you can’t access the browser’s DOM or do anything specific to browser-hosted JavaScript.

The closest you could get is using something like browserify to include Node.js modules in your client-side code.