Piotr Berebecki
Piotr Berebecki

Reputation: 7468

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"
  },

Upvotes: 9

Views: 9435

Answers (1)

trincot
trincot

Reputation: 350310

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');
    });
});

Upvotes: 9

Related Questions