Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.simulate('click') only working when done twice on the same component, through ID and Class

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.

like image 326
nxmohamad Avatar asked Oct 30 '22 03:10

nxmohamad


1 Answers

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.

like image 63
nxmohamad Avatar answered Nov 09 '22 16:11

nxmohamad