[英]Jest testing of simple vanilla JavaScript - Cannot read property 'addEventListener' of null
I'm trying to test my app using Jest and Node.js. 我正在尝试使用Jest和Node.js来测试我的应用程序。 What is the correct setup to avoid getting the following error in the terminal when running tests with JestJS?
在使用JestJS运行测试时,避免在终端中出现以下错误的正确设置是什么?
Cannot read property 'addEventListener' of null
无法读取null的属性'addEventListener'
The test for the sum
function passes as soon as I comment out adding the event listener in the app.js
file. 一旦我注释掉在
app.js
文件中添加事件监听器, sum
函数的测试就会通过。 I'm not even sure why is this line as well as the console.log('Not part...')
executed by Jest since I only export the sum
function. 我甚至不确定为什么这条线以及由Jest执行的
console.log('Not part...')
因为我只导出sum
函数。
The contents of my index.html file: 我的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>
The contents of my app.js file: 我的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
};
The contents of my app.test.js file: 我的app.test.js文件的内容:
var { sum } = require('./app');
describe('sum', () => {
test('adds numbers', () => {
expect(sum(1, 2)).toBe(3);
});
});
My package.json: 我的package.json:
"scripts": {
"test": "jest --coverage",
"test:watch": "npm run test -- --watch"
},
getElementById
might execute before the DOM is loaded. getElementById
可能在加载DOM之前执行。 Put that code block in a callback that is executed when the document has been loaded. 将该代码块放入文档加载时执行的回调中。 For instance:
例如:
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');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.