2
我试图用Jest和Node.js测试我的应用程序。使用JestJS运行测试时,避免在终端中出现以下错误的正确设置是什么?Jest测试简单的香草JavaScript - 无法读取属性'addEventListener'null
无法读取空
为sum
功能测试,一旦通过的特性“的addEventListener”我注释掉app.js
文件中添加事件侦听器。我甚至不知道为什么这条线以及由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'可能执行得太快。也许把这个代码块放在'window.load = function(){...}'中。 – trincot
这实际上解决了这个问题。谢谢:)我很高兴接受它作为解决方案。 –