我正在尝试将Mocha集成到我的应用中,但是遇到document is not defined
错误。我也尝试集成JSDOM来解决此问题,但是没有运气。也许我的实现是错误的。预先感谢!
注意:我正在本地进行测试,但是稍后将在Amazon EC2上进行托管。在服务器上实时托管时,文档错误会自行消失吗?
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;
答案 0 :(得分:1)
问题是您在声明文档之前在全局范围内require
使用了document
的代码。
var assert = require('assert');
var jsdom = require('mocha-jsdom');
global.document = jsdom();
var test = require('../index.js');
describe('Mutliply', function() { ...
应该工作,甚至
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());
});
});
答案 1 :(得分:1)
您可以尝试使用 JSDom 为 Node 添加 Dom 支持:
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
global.document = new JSDOM(html).window.document;