简单香草的玩笑测试 JavaScript - 无法读取 null 的 属性 'addEventListener'

Jest testing of simple vanilla JavaScript - Cannot read property 'addEventListener' of null

我正在尝试使用 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');
    });
});