Testing JavaScript Event Listeners with Jest

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

In this blog post, you will learn how to mock JavaScript events such as addEventListener, onclick, and DOMContentLoaded using Jest. While the examples provided focus on these specific events, Jest allows you to mock any JavaScript event listener.

Let’s start with a simple example. Suppose you have the following JavaScript function:

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

The init function calls the instance method when the DOMContentLoaded event is triggered.

Now, let’s write a 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
    .mockImplementationOnce((event, callback) => {

In this test case, we use Jest’s mocking capabilities. We mock document.addEventListener using jest.fn() and provide a custom implementation that triggers the callback immediately. By doing so, we simulate the DOMContentLoaded event and ensure that the instance method is called.

Mocking allows you to create controlled test environments where you can replace real objects with custom implementations. This helps isolate the code under test and focus on specific scenarios without worrying about the behavior of external dependencies. Jest provides a comprehensive mocking system, including mock functions and module mocking, to facilitate this process.

Happy Coding!

Next Post Previous Post
  • 545himanshu
    545himanshu July 24, 2022 at 10:33 PM

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

    • Anonymous
      Anonymous May 4, 2023 at 7:36 AM

      sorry I see you comment very late. I will get back to you soon

Add Comment
comment url