3
votes

I'm using Jest and Enzyme to test out a Form component, and I'm having trouble getting the click simulation to work. For reference: Button is a styled rebass Button, and exists in the form like this:

<Button
  type="reset"
  disabled={pristine || submitting}
  onClick={() => onClose(dirty)}
>

Here's the test that's failing:

 it('should handle the onClose event', () => {
      const onCloseSpy = jest.fn();
      const renderedComponent = mount(renderFormUtil({ onClose: onCloseSpy }));
      expect(onCloseSpy).not.toHaveBeenCalled();
      console.log(renderedComponent.find(Form).props().onClose);
      renderedComponent
      .find(Button)
      .first()
      .simulate('click');
    expect(onCloseSpy).toHaveBeenCalled();
  });

What should be noted here, is that if I replace the simulate line with the following:

renderedComponent
  .find(Button)
  .first()
  .props()
  .onClick();

then suddenly my test passes. How is this possible? If the onClick prop is correct, then doesn't that mean the click event is not calling the prop correctly?

1
Why do you use .find(ButtonSubmit) in one case and .find(Button) in the other? I don't know what Button looks like, but I wouldn't expect the same result, since you are testing two different components.Michael Jungo
Sorry, those are the same component-- I meant to get rid of the word Submit in the component name, for simplificationEthan Neidhart

1 Answers

0
votes

It's not clear if the two .find select the same components because each one uses a different selector. Combined with that you are using .first() which it's not possible to be sure about the order with the sample code.
You can try to use a more specific selector, avoiding to use .first() and getting the desired component just with .find. For that you can add an id for a specific ButtonSubmit and use a selector like:
.find('ButtonSubmit[id="foo"]')