Home > OS >  Spy on a function inside function component using React testing library
Spy on a function inside function component using React testing library

Time:09-24

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?

CodePudding user response:

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();
});

CodePudding user response:

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.

  • Related