3
votes

I am testing a react component which contains a form(using formik) and I need to test if on submit button clicked, whether submit function is called or not.

at the moment, the test is failing. now, the form has required fields schema too using yup so, I was wondering whether I need to fill up all the fields before testing it. because at the moment, it doesnt submit until the form has errors i.e. if the required fieldss are empty. so does that obstruct the testing of the button click and the function being called or not?

describe('submitform', () => {
  let wrapper = '';
  const handleSubmit = jest.fn();
  beforeEach(() => {
        wrapper = mount(<ExampleButton  >
                          <span className="visible-sm">Next</span>
                          <span className="visible-xs font-entity">
                            &rsaquo;
                          </span>
                          </ExampleButton>
        );
      });
  afterEach(() => {
        wrapper.unmount();
      });
  it('call function on click',async ()=> {    

    // let btn = wrapper.find('#btnEx').find('button').find('#btnEx');
    let btn = wrapper.find('button').simulate('click');
    console.log('wrapper : ',btn.debug());
    // btn.props().onClick();
    expect(handleSubmit).toHaveBeenCalled();
  });
})

how do I fill up the fields then, before testing? or is it even required for me to fill up the fields before testing on click?

1
does ExampleButton component contain a form(if so its name is really confusing)? where do you pass handleSubmit mock? what does mean "test is failing"? is it about function has not been called or something else?skyboyer

1 Answers

0
votes

You need a way to pass your mock handleSubmit function to your ExampleButton

If ExampleButton has onSubmit event handler prop, this is easier:

// ExampleButton.jsx
const ExampleButton = ({ onSubmit }) => <button type="submit" onClick={onSubmit} />;

// ExampleButton.test.jsx
const handleSubmit = jest.fn();
...
wrapper = mount(<ExampleButton onSubmit={handleSubmit} />);

If ExampleButton has inner event handler function, kinda tricky

// ExampleButton.jsx
const ExampleButton = () => {
  const handleSubmit = (params) => {...}
  return <button type="submit" onClick={handleSubmit} />;
}

// ExampleButton.test.jsx
wrapper = mount(<ExampleButton onSubmit={handleSubmit} />);
wrapper.find('button').simulate('click', mockParams);