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

180
Visualizações
Spy on a function inside functional component using React testing library

I'm trying to spy on a function inside a function component using react testing library. I wanted to test whether handleClick function has been called whenever the button is clicked.

Here's excerpt from my code

Component

const Foo = () => {
  
  const handleClick = () => {}

  return <div>
     <button data-testid="button" onClick={handleClick}>Continue</button>
  </div>
}

Test case

  it("should handle continue button click", async () => {
    const { getByTestId } = render(<Foo />);
    const button = getByTestId("button");
    const spy = jest.spyOn(Foo, "handleClick");
    act(() => {
      fireEvent.click(button);
    });
    expect(spy).toHaveBeenCalled();
  });

The error I'm getting is as below

Cannot spy the handleClick property because it is not a function; undefined given instead

Could anyone please help?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are trying to spy on handleClick as if it was a property of Foo, which is a function.

I can move handleClick to another file and import it both in the component and the test:

handler.js

export const handleClick = () => {}

Component

import { handleClick } from './handler.js'
const Foo = () => {

return <div>
   <button data-testid="button" onClick={handleClick}>Continue</button>
</div>
}

Test case

import * as handlers from './handler.js';

it("should handle continue button click", async () => {
  const { getByTestId } = render(<Foo />);
  const button = getByTestId("button");
  const spy = jest.spyOn(handlers, "handleClick");
  act(() => {
    fireEvent.click(button);
  });
  expect(spy).toHaveBeenCalled();
});
about 4 years ago · Juan Pablo Isaza Relatório

0

You don't want to spy on handleClick. Instead, you want to test what effect handleClick had on the component. Your handleClick callback is an implementation detail, and as a general rule, you don't test that.

about 4 years ago · Juan Pablo Isaza Relatório
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