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

178
Views
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 answers
Answer question

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 Report

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 Report
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!