Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enzyme simulate submit form, Cannot read property 'value' of undefined

I'm having some difficulty testing a component with jest and enzyme. What I would like to do is test submitting the form without a value in the name field. This will make certain that the component is displaying an error. However, when I run the rest I am getting an error in my console:

TypeError: Cannot read property 'value' of undefined

I'm fairly new to front-end testing, and testing in general. So, I'm not entirely sure I'm using enzyme correctly for this type of test. I don't know if my tests are incorrect or if I've just written a component that is not easily tested. I'm open to changing my component if that will make it easier to test?

Component

class InputForm extends Component {
  constructor(props) {
    super(props);
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onFormSubmit(e) {
    e.preventDefault();
    // this is where the error comes from
    const name = this.name.value;
    this.props.submitForm(name);
  }

  render() {
    let errorMsg = (this.props.validationError ? 'Please enter your name.' : null);
    return (
      <form onSubmit={(e) => this.onFormSubmit(e)}>
        <input
          type="text"
          placeholder="Name"
          ref={ref => {
                 this.name = ref
               }}
        />
        <p className="error">
          {errorMsg}
        </p>
        <input
          type="submit"
          className="btn"
          value="Submit"
        />
      </form>
      );
  }
}
InputForm.propTypes = {
  submitForm: React.PropTypes.func.isRequired,
};

Test

  // all other code omitted
  // bear in mind I am shallow rendering the component

  describe('the user does not populate the input field', () => {

    it('should display an error', () => {
      const form = wrapper.find('form').first();
      form.simulate('submit', {
        preventDefault: () => {
        },
        // below I am trying to set the value of the name field
        target: [
          {
            value: '',
          }
        ],
      });
      expect(
        wrapper.text()
      ).toBe('Please enter your name.');
    });

  });
like image 929
j_quelly Avatar asked Dec 23 '16 05:12

j_quelly


1 Answers

I think that you don't need to pass event object to simulate the submit event. This should work.

  describe('the user does not populate the input field', () => {

    it('should display an error', () => {
      const form = wrapper.find('form').first();
      form.simulate('submit');
      expect(
        wrapper.find('p.error').first().text()
      ).toBe('Please enter your name.');
    });

  });
like image 75
WitVault Avatar answered Sep 23 '22 01:09

WitVault