javascript - 简单普通 JavaScript 的开 Jest 测试 - 无法读取 null 的属性 'addEventListener'

标签 javascript node.js testing jestjs

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

Cannot read property 'addEventListener' of null

当我注释掉在 app.js 文件中添加事件监听器时,sum 函数的测试通过了。我什至不确定为什么 Jest 会执行这一行以及 console.log('Not part...') 因为我只导出了 sum 函数.

enter image description here

我的 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/

相关文章:

javascript - 使用 textContent 更改/添加我的 html 文件中的文字

Xcode 5 测试未运行

php - 一次在 PHPunit 中运行所有测试,但彼此隔离

javascript - 使用纯原型(prototype)方法的 Javascript 中的寄生继承

javascript - 使用 jquery 创建时数据库生成的列表不起作用

javascript - 向下滚动时如何动态偏移顶部栏高度

javascript - 使用 gulp 在页面上临时添加脚本

javascript - 在javascript中循环遍历缓冲区

node.js - Mongoose 中的 ArrayFilter

安卓 Espresso : Wait for Activity to finish/start