Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
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);
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!