Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

285
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda