首页 文章

酶模拟提交表单,无法读取未定义的属性'value'

提问于
浏览
4

我在使用jest和酶测试组件时遇到了一些困难 . 我想要做的是测试在名称字段中提交没有值的表单 . 这将确保组件显示错误 . 但是,当我运行其余的时,我在控制台中收到错误:

TypeError:无法读取undefined的属性“value”

我对前端测试和一般测试都很陌生 . 所以,我不完全确定我正在使用酶进行这种类型的测试 . 我不知道我的测试是否不正确,或者我是否刚编写了一个不易测试的组件 . 我愿意改变我的组件,如果这样可以更容易测试吗?

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.');
    });

  });

3 回答

  • 2

    根据经验,你应该尽可能避免使用refs,为什么? here

    在你的情况下,我建议一个更好的方法可能是:

    class InputForm extends Component {
          constructor(props) {
            super(props);
            this.state = {
                name : ''
            }
            this.onFormSubmit = this.onFormSubmit.bind(this);
            this.handleNameChange = this.handleNameChange.bind(this);
          }
    
    
          handleNameChange(e){
            this.setState({name:e.target.value})
          }
    
          onFormSubmit(e) {
            e.preventDefault();
            this.props.submitForm(this.state.name);
          }
    
          render() {
            let errorMsg = (this.props.validationError ? 'Please enter your name.' : null);
            return (
              <form onSubmit={(e) => this.onFormSubmit(e)}>
                <input
                  type="text"
                  placeholder="Name"
                  onChange={this.handleNameChange}
                />
                <p className="error">
                  {errorMsg}
                </p>
                <input
                  type="submit"
                  className="btn"
                  value="Submit"
                />
              </form>
              );
          }
        }
    

    我想这会解决你的问题 . 有了这个,你的测试应该运行良好 .

  • 2

    我认为您不需要传递事件对象来模拟提交事件 . 这应该工作 .

    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.');
        });
    
      });
    
  • 0

    该问题已在this thread中讨论过 .
    这个解决方案适合我 .

    import { mount, shallow } from 'enzyme';
      import InputForm from '../InputForm':
      import React from 'react';
      import { spy } from 'sinon';
    
      describe('Form', () => {
        it('submit event when click submit', () => {
          const callback = spy();
          const wrapper = mount(<InputForm />);
          wrapper.find('[type="submit"]').get(0).click();
          expect(callback).to.have.been.called();
        });
      });
    

    它使用摩卡柴而不是开玩笑 . 但是你可以知道如何去做 .

相关问题