最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - 'ReferenceError: document is not defined' error - Stack Overflow

programmeradmin5浏览0评论

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;

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;
Share Improve this question edited Aug 5, 2018 at 22:26 Jonathan Hall 79.9k19 gold badges159 silver badges203 bronze badges asked Aug 2, 2018 at 20:32 en6in33ren6in33r 2661 gold badge5 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

The problem is you're requireing 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());
  });
});

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;
发布评论

评论列表(0)

  1. 暂无评论