'ReferenceError: document is not defined' error
14,333
Solution 1
The problem is you're require
ing the code that uses document
in the global scope before you declare the document.
var assert = require('assert');
var jsdom = require('mocha-jsdom');
global.document = jsdom();
var test = require('../index.js');
describe('Mutliply', function() { ...
should work, or even
var assert = require('assert');
var jsdom = require('mocha-jsdom');
global.document = jsdom();
describe('Mutliply', function() {
var test = require('../index.js'); // late import
it('should equal 9 when multiply is called', function() {
assert.equal(9, test.multiply());
});
});
Solution 2
You could try to use JSDom to add Dom support to Node:
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
global.document = new JSDOM(html).window.document;
Author by
Simon Wong
Updated on June 18, 2022Comments
-
Simon Wong almost 2 years
I'm trying to integrate Mocha into my app, but am getting
document is not defined
error. I've also tried to integrate JSDOM to resolve this but no luck there. Perhaps my implementation is wrong. Thanks in advance!Note: I'm testing this locally, but will host this on Amazon EC2 later. Would the document error go away on it's own when hosted live on a server?
test.js
var test = require('../index.js'); var assert = require('assert'); var jsdom = require('mocha-jsdom'); global.document = jsdom(); describe('Mutliply', function() { jsdom(); it('should equal 9 when multiply is called', function() { assert.equal(9, test.multiply()); }); });
index.js
'use strict'; let test = {}; let movieList = document.getElementById('movie-list'); //bunch of code test.multiply = function() { return 3*3; } module.exports = test;
-
Simon Wong almost 6 yearsImporting it later did solve the document is undefined issue but now, I'm getting
TypeError: Cannot read property 'getElementById' of undefined
. It sounds like document is still undefined. -
AKX almost 6 yearsWell, mocha-jsdom's readme says it's deprecated - maybe try github.com/rstacruz/jsdom-global which is linked there?