Testing JavaScript Event Listeners with Jest

Jest is a JavaScript testing framework maintained by Facebook, Inc. designed and built by Christoph Nakazawa with a focus on simplicity and support for large web applications. It works with projects using Babel, TypeScript, Node.js, React, Angular, Vue.js and Svelte. Wikipedia

In this post, you will learn how to mock Javascript event like addEventListener,onclick and DOMContentLoaded using Jest. This is not limited to these listed events, but you can mock all javascript event listeners with the jest.

Let’s start the tutorial. Suppose you have the following javascript function

module.exports = {
  init: function () {
    document.addEventListener("DOMContentLoaded", () => {
      this.instance();
    });
  },
  instance: function () {
    console.log("Instance method called");
  }
};

You can see we are calling the instance method when the document is loaded.
Let’s write the test case for the above function using jest.

import eventModule from "./event";

test("It should pass", () => {
  const instanceMock = jest.spyOn(eventModule, "instance");
  document.addEventListener = jest
    .fn()
    .mockImplementationOnce((event, callback) => {
      callback();
    });
  eventModule.init();
  expect(document.addEventListener).toBeCalledWith(
    "DOMContentLoaded",
    expect.any(Function)
  );
  expect(instanceMock).toBeCalledTimes(1);
});

As you can see, I am mocking document.addEventListener using jest and then asserting on the spy function.

Happy Coding :)

1 Comments

Please do not post any spam link in the comment box😊

  1. hello , actually i wanna test on eventsource.addeventlistener using jest+react testing lib. can u guide me for that

    ReplyDelete
Post a Comment
Previous Post Next Post