'Jest (test case is failing) - Click should invoke the function in testing

I'm trying to write a test case where I'm mocking addEventListener and after that is should invoke the callback function but I'm getting this error: expect(jest.fn()).toBeCalledWith(...expected) Expected: "click", Any Number of calls: 0

So when I removed button from my javascript file and just did experiment to click on document, my test case worked fine(I changed test case also used document.addEventlistener instead of element). So my mock calling logic is correct but its not working if I use the button. Anyone has any idea how button will invoke in jest test.

Here is my test.js file

let btn = document.createElement("button");
 btn.type = "button";
let buttonNode = document.createTextNode("submit");
btn.appendChild(buttonNode);
document.body.appendChild(btn);
 function init() {
  btn.addEventListener("click", () => {
        this.instance();
      });
    }
   function instance() {
      console.log("Instance method called");
    }
 
 
 init();
  const exportFunctions = {
    init,
    instance,
  };
  module.exports = exportFunctions;

Here is my example.test.js file

const test1 = require("./test");

test("It should pass", () => {
 document.body.innerHTML = `
<button type="button">Submit</button>
`;
const element = document.getElementsByTagName("button")[0];
  const instanceMock = jest.spyOn(test1, "instance");
  element.addEventListener = jest
    .fn()
    .mockImplementationOnce((event, callback) => {
      callback();
    });
  test1.init();
  
  expect(element.addEventListener).toBeCalledWith(
    "click",
    expect.any(Function)
  );

  expect(instanceMock).toBeCalledTimes(1);
});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source