2017-03-04 118 views
2

我试图用Jest和Node.js测试我的应用程序。使用JestJS运行测试时,避免在终端中出现以下错误的正确设置是什么?Jest测试简单的香草JavaScript - 无法读取属性'addEventListener'null

无法读取空

sum功能测试,一旦通过的特性“的addEventListener”我注释掉app.js文件中添加事件侦听器。我甚至不知道为什么这条线以及由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" 
    }, 
+1

'getElementById'可能执行得太快。也许把这个代码块放在'window.load = function(){...}'中。 – trincot

+0

这实际上解决了这个问题。谢谢:)我很高兴接受它作为解决方案。 –

回答

2

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'); 
    }); 
}); 
相关问题