I am trying to test a React component and make sure that when its button gets clicked, the correct method gets invoked. However, when I try to run my test and try to spy on that method, I get the following message:
Error: Cannot spyOn on a primitive value; undefined given
How do I test that when a button is clicked the correct method is invoked? Thanks!
sampleComponent.jsx:
import * as React from 'react';
const SampleComponent = () => {
const sampleMethod = () => {
console.log('hello world');
};
return <button onClick={sampleMethod} type="button">Click Me</button>;
};
export default SampleComponent;
sampleComponent.test.jsx:
import * as React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sample';
test('testing spy', () => {
const spy = jest.spyOn(SampleComponent.prototype, 'sampleMethod');
const wrapper = shallow(<SampleComponent />);
wrapper.find('button').simulate('click');
expect(spy).toHaveBeenCalled();
});