Jesttesting简单的香草JavaScript – 不能读取null的属性'addEventListener'

我试图用Jest和Node.js来testing我的应用程序。 使用JestJS运行testing时,避免在terminal中出现以下错误的正确设置是什么?

无法读取null的属性“addEventListener”

sum函数的testing通过我注释掉在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可能在加载DOM之前执行。 将该代码块放入文档加载时执行的callback中。 例如:

 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'); }); });