Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

293
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda