【问题标题】:"ReferenceError: document is not defined"“ReferenceError:文档未定义”
【发布时间】:2020-01-08 15:36:32
【问题描述】:

下午好,我开始处理 jsdom。为了清楚起见,写了一个非常简单的函数。使用 mocha、chai 和 JSDOM 编写了一个测试。

我的module.js 中的所有“文档”都被隐藏了,因为如果我取消注释它们,就会出现错误"ReferenceError: document is not defined"。理论上,我已经明白它的意思了。此错误表示Node 中没有窗口、文档等。但我不知道如何解决这个问题。

如果有任何帮助,我将不胜感激。

index.html:

<body>
  <input type="text" id="inputValue">
  <input type="text" id="outputValue">
  <button id="getResult">getResult</button>

  <script src="./module.js"></script>
</body>

module.js

//var input = document.getElementById("inputValue");
//var output = document.getElementById("outputValue");
//var button = document.getElementById("getResult").addEventListener('click', generateValue);

function generateValue(input, output){
    output.value = input.value * 5;
}

module.exports = {
    generateValue,
};

tests.js

    let object = require("../module.js");
const assert = require("chai").assert;
const { JSDOM } = require("jsdom");

describe("generateValue", function() {
    let dom = null;
    before(async function() {
        dom = new JSDOM('<!doctype html><html><head></head><body></body></html>')
    });

    it('Should return 25 when parameter 5', function() {
        const input = dom.window.document.createElement("input");
        input.id = "inputValue";
        const output = dom.window.document.createElement("input");
        output.id = "outputValue";
        dom.window.document.body.append(input);
        dom.window.document.body.append(output);
        input.value = 5;
        const expected = 25;

        object.generateValue(input, output);
        assert.equal(output.value, expected);
    });
});

【问题讨论】:

    标签: javascript unit-testing mocha.js jsdom


    【解决方案1】:

    首先:您不能在模块之外导出或导入
    这意味着该节点不能在 html 中使用,除非您像这样向浏览器声明:script tag =>
    节点在控制台中运行(命令提示符,如 c++),html 在浏览器中运行...

    第二:
    为什么要生成值并导出您可以在 test.js 文件中执行此操作
    如果你想这样做,你必须像 PHP 一样使用 node 作为服务器。(有一点不同)

    顺便说一句,您可以使用另一个 js 文件计算生成值,然后显示(或您想要的所有东西)并使用异步函数来获取值并做一些事情..... 但您必须在其中添加另一个脚本标签html 文件

    记住你不能在 HTML 中使用像 JS 文件一样的 Node 这就是为什么我们在 node.js 中没有文档和窗口

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多