admin管理员组

文章数量:1398999

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;

本文标签: javascript39ReferenceError document is not defined39 errorStack Overflow