2017-03-04 122 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'); 
    }); 
}); 
相關問題