Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest testing of simple vanilla JavaScript - Cannot read property 'addEventListener' of null

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.

enter image description here

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"
  },
like image 608
Piotr Berebecki Avatar asked Mar 04 '17 11:03

Piotr Berebecki


People also ask

Can't read property addEventListener of null solve?

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 ...

Does jest work with vanilla JavaScript?

Jest is a JavaScript Testing Framework focus on simplicity. It works with frameworks like Angular or libraries like React. Also, with Vanilla JavaScript.

Do you need jest and Cypress?

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.


1 Answers

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');
    });
});
like image 168
trincot Avatar answered Sep 24 '22 15:09

trincot