【发布时间】:2019-11-28 12:45:50
【问题描述】:
我创建了一个非常简单的页面,它只显示一条消息,因为我正在尝试测试 JSDOM 以使用document。但是,我收到以下错误。
首先,我在网上看过无数的例子,除了Stack Overflow上贴的问题,我连最简单的例子都解决不了。作为旁注,我是 Javascript 新手。
到目前为止我的代码如下:
根目录
--->index.html
--->module.js
--->package-lock.json
--->package.json
--->测试
--->--->messageTest.js
不同的文件如下:
index.html
<!doctype html>
<head>
<meta charset="utf-8">
<title>jsdom Unit Test</title>
</head>
<body>
<p id='msg'>Hello, World!</p>
<script src="module.js"></script>
</body>
</html>
module.js
function updateMsg(newMsg) {
document.getElementById('msg').innerHTML = newMsg;
}
updateMsg("Changing message");
module.exports = updateMsg;
package.json
{
"name": "message-example",
"version": "1.0.0",
"description": "Testing how to use the JSDOM",
"main": "module.js",
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC",
"devDependencies": {
"chai": "^4.2.0",
"jsdom": "^15.1.1",
"mocha": "^6.2.0",
"mocha-jsdom": "^2.0.0",
"rewire": "^4.0.1",
"sinon": "^7.3.2"
}
}
messageTest.js
var updateMsg = require('../module.js');
const expect = require('chai').expect
const { JSDOM } = require('jsdom');
describe('updateMsg', function () {
before(function() {
return JSDOM.fromFile('index.html')
.then((dom) => {
global.window = dom.window;
global.document = window.document;
});
})
it ('updates the innerHTML of element with id "msg"', function () {
expect(document.getElementById('msg').innerHTML).to.equal('Hello, World!');
updateMsg('The new msg!');
expect(document.getElementById('msg').innerHTML).to.equal('The new msg!');
});
});
如果我使用npm test 运行测试,我会在module.js 文件中的document.getElementByID... 步骤中收到ReferenceError: document is not defined 错误。
如果我删除updateMsg("Changing message"),我的测试显然运行良好。
【问题讨论】:
-
您的代码似乎运行良好,它在 标记中显示文本“正在更改消息”,检查小提琴:jsfiddle.net/7k96oeuw 而且,它不像您描述的那样
document.getElementByID,是document.getElementById -
感谢您的收获。我的代码确实运行良好(在物理浏览器上),但是当我在需要模拟浏览器的地方运行测试时,我发现找不到文档元素。这应该用JSDOM模拟(据我所知),但我不确定为什么它不起作用。
标签: javascript html json dom jsdom