JestとNode.jsを使用して自分のアプリケーションをテストしようとしています。 JestJSでテストを実行しているときに端末で次のエラーが発生するのを避けるための正しい設定は何ですか?単純なバニラのJestテストJavaScript - nullのプロパティ 'addEventListener'を読み取ることができません
プロパティを読み取ることができませんヌルの「addEventListenerを」
sum
機能のためのテストはすぐに私がapp.js
ファイルにイベントリスナーを追加することコメントアウトとして渡します。私はsum
関数をエクスポートするだけなので、なぜこの行だけでなく、Jestによって実行されたconsole.log('Not part...')
もなぜわからないのですか。
私の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:DOMがロードされる前に
"scripts": {
"test": "jest --coverage",
"test:watch": "npm run test -- --watch"
},
'getElementById'はあまりにも早く実行されるかもしれません。たぶん、そのコードブロックを 'window.load = function(){...}'に入れてください。 – trincot
これは実際に問題を削除しました。ありがとうございました:)私はそれを解決策として受け入れてうれしいです。 –