Pio*_*cki 6 javascript testing node.js jestjs
我正在尝试使用 Jest 和 Node.js 测试我的应用程序。使用 JestJS 运行测试时,避免在终端中出现以下错误的正确设置是什么?
无法读取 null 的属性“addEventListener”
sum一旦我注释掉在app.js文件中添加事件侦听器,该函数的测试就会通过。我什至不确定为什么这一行以及console.log('Not part...')Jest 执行的行,因为我只导出该sum函数。
我的 index.html 文件的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<button id="button">JavaScript</button>
<script src="./app.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的 app.js 文件的内容:
function sum(a, b) {
return a + b;
}
console.log('Not part of module.exports but still appearing in terminal, why?');
var button = document.getElementById('button');
button.addEventListener('click', function(e) {
console.log('button was clicked');
});
module.exports = {
sum
};
Run Code Online (Sandbox Code Playgroud)
我的 app.test.js 文件的内容:
var { sum } = require('./app');
describe('sum', () => {
test('adds numbers', () => {
expect(sum(1, 2)).toBe(3);
});
});
Run Code Online (Sandbox Code Playgroud)
我的 package.json:
"scripts": {
"test": "jest --coverage",
"test:watch": "npm run test -- --watch"
},
Run Code Online (Sandbox Code Playgroud)
getElementById可能会在 DOM 加载之前执行。将该代码块放在加载文档时执行的回调中。例如:
document.addEventListener('DOMContentLoaded', function () {
console.log('Not part of module.exports but still appearing in terminal, why?');
var button = document.getElementById('button');
button.addEventListener('click', function(e) {
console.log('button was clicked');
});
});
Run Code Online (Sandbox Code Playgroud)