I have gone through existing issues and could not find one similar to this.
I have a button element like so, that sits within a <Contact/>
component that I am testing:
<div>
...
<button id="Contact-button-submit" className="btn btn-primary btn-lg" onClick={this.handleSubmit}>Submit</button>
...
</div>
and here is my test:
it('calls handleSubmit when Submit button is clicked', () => {
let wrapper = shallow(<Contact {...mockProps} />);
wrapper.instance().handleSubmit = jest.fn();
let { handleSubmit } = wrapper.instance();
expect(handleSubmit).toHaveBeenCalledTimes(0);
wrapper.find('#Contact-button-submit').simulate('click'); // the only simulate click I want
wrapper.find('.btn-primary').simulate('click'); // the simulate click I also had to add
expect(handleSubmit).toHaveBeenCalledTimes(1);
});
The funny thing is that, when I only include the first simulate click (the ID one), the test fails at the last expect. The onClick function (handleSubmit) is never called. But when I add the second one that uses className, it passes.
It seems like they BOTH need to be present. It will fail if one is removed.
Are there any known causes for this? I'm scratching my head over this.
the solution for me was to use jest.spyOn
it('calls handleSubmit when Submit button is clicked', () => {
const handleSubmit = jest.spyOn(Contact.prototype, 'handleSubmit');
let wrapper = shallow(<Contact {...mockProps} />);
expect(handleSubmit).toHaveBeenCalledTimes(0);
wrapper.find('#Contact-button-submit').prop('onClick')();
expect(handleSubmit).toHaveBeenCalledTimes(1);
});
the issue was that I was stubbing the method after shallow rendering it, when in fact I needed to do that before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With