I'm trying to test my app using Jest and Node.js. What is the correct setup to avoid getting the following error in the terminal when running tests with JestJS?
Cannot read property 'addEventListener' of null
The test for the sum
function passes as soon as I comment out adding the event listener in the app.js
file. I'm not even sure why is this line as well as the console.log('Not part...')
executed by Jest since I only export the sum
function.
The contents of my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<button id="button">JavaScript</button>
<script src="./app.js"></script>
</body>
</html>
The contents of my app.js file:
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
};
The contents of my app.test.js file:
var { sum } = require('./app');
describe('sum', () => {
test('adds numbers', () => {
expect(sum(1, 2)).toBe(3);
});
});
My package.json:
"scripts": {
"test": "jest --coverage",
"test:watch": "npm run test -- --watch"
},
We can fix the “cannot read property addEventListener' of null” error in JavaScript by ensuring that the correct selector is defined, adding a null check to the element before calling addEventListener() , moving the script tag to the bottom of the body, or accessing the element in a DOMContentLoaded event listener ...
Jest is a JavaScript Testing Framework focus on simplicity. It works with frameworks like Angular or libraries like React. Also, with Vanilla JavaScript.
short answers: It's very common to use Jest and Cypress in the same codebase. With component Libraries like Vue and React, the line between integration and unit tests can get a bit fuzzy.
getElementById
might execute before the DOM is loaded. Put that code block in a callback that is executed when the document has been loaded. For instance:
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');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With