我正在尝试使用 Jest 和 Node.js 测试我的应用程序。在使用 JestJS 运行测试时,避免在终端中出现以下错误的正确设置是什么?
Cannot read property 'addEventListener' of null
当我注释掉在 app.js
文件中添加事件监听器时,sum
函数的测试通过了。我什至不确定为什么 Jest 会执行这一行以及 console.log('Not part...')
因为我只导出了 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>
我的 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
};
我的 app.test.js 文件的内容:
var { sum } = require('./app');
describe('sum', () => {
test('adds numbers', () => {
expect(sum(1, 2)).toBe(3);
});
});
我的 package.json:
"scripts": {
"test": "jest --coverage",
"test:watch": "npm run test -- --watch"
},
最佳答案
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');
});
});
关于javascript - 简单普通 JavaScript 的开 Jest 测试 - 无法读取 null 的属性 'addEventListener',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42595427/