This is a simple React component. I'm using React Testing Library for unit testing components and I was not able to test the handleClick function of TestComponent using jest.spyOn(). Could anyone please help?
Component
import React from 'react';
const Button = (props) => (
<button onClick={props.handleClick}> {props.text}</button>
);
const TestComponent = () => {
const handleClick = () => {
console.log('clicked!');
};
return (
<div>
<Button text="Test Button" handleClick={handleClick} />
</div>
);
};
export default TestComponent;
Test
it('expect spy to be called', () => {
const { getByText } = render(<TestComponent />);
const spy = jest.spyOn(TestComponent, 'handleClick');
const button = getByText('Test Button');
fireEvent.click(button);
expect(spy).toHaveBeenCalled();
});
The error that I'm getting is below. I tried using TestComponent.prototype in jest.spyOn but that does not help either.
Cannot spy the handleClick property because it is not a function; undefined given instead