React,如何模拟用户输入进行单元测试?

React, how to simulate user input for unit testing?

我一直在尝试对接受用户输入的 React 组件进行单元测试。更具体地说,我正在尝试测试反应组件中的 onChange 函数。但是我似乎无法设置输入值,我尝试了互联网上建议的几种不同方法并且 none 似乎有效。下面是我要测试的组件。

class Input extends Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    /* Check if max length has been set. If max length has been
    set make sure the user input is less than max Length, otherwise
    return before updating the text string. */
    if(this.props.maxLength) {
      if(event.target.value.length > this.props.maxLength) {
        return;
      }
    }
    this.setState({ value: event.target.value });
  }

  render () {
    const { disabled, label, maxLength, multiline, type, value, ...others} = this.props;
    const theme = themeable(others.theme);

    let inputClassName = classNames({
      "input": type !== 'checkbox',
      "checkbox": type == 'checkbox',
      disabled,
      multiline,
      value,
      [`${this.props.className}`]: !!this.props.className
    });

    return (
      <div {...theme(1, 'container')}>
        {this.props.label ? <label htmlFor={this.props.htmlFor} {...theme(2, 'label')}>{label}</label> : null}
          <input value={this.state.value} {...theme(3, ...inputClassName)} onChange={this.handleChange} type={type} />
      </div>
    );
  }
}

我发现了这个问题:https://github.com/airbnb/enzyme/issues/76 并尝试了底部的建议,我总是得到未定义或空白字符串。我尝试了 levibuzolic 使用酶的模拟变化的建议,如下所示。然而这只是 returns AssertionError: expected '' to equal 'abcdefghij'

it('Make sure inputted text is shorter than max length', function() {
    const result = mount(<Input maxLength={10}></Input>);
    result.find('input').simulate('change', {target: {value: 'abcdefghijk'}});
    expect(result.state().value).to.equal("abcdefghij");
});

然后我尝试了下面takkyuuplayer的建议。这也因 AssertionError: expected '' to equal 'abcdefghij'

而失败
  it('Make sure inputted text is shorter than max length', function() {
    const result = mount(<Input maxLength={10}></Input>);
    result.find('input').node.value = 'abcdefghijk';
    expect(result.state().value).to.equal("abcdefghij");
  });

我找到了这篇文章:https://medium.com/javascript-inside/testing-in-react-getting-off-the-ground-5f569f3088a#.f4gcjbaak 并尝试了他们的方法,但也失败了。

  it('Make sure inputted text is shorter than max length', function() {
    const result = mount(<Input maxLength={10}></Input>);
    let input = result.find('input');
    input.get(0).value = 'abcdefghijk';
    input.simulate('change');
    expect(result.state().value).to.equal("abcdefghij");
  });

最后我尝试使用 Simulating text entry with reactJs TestUtils 建议的反应测试实用程序,下面是我尝试的代码,但是失败并显示错误消息:TypeError: Cannot read property '__reactInternalInstance$z78dboxwwtrznrmuut6wjc3di' of undefined

  it('Make sure inputted text is shorter than max length', function() {
    const result = mount(<Input maxLength={10}></Input>);
    let input = result.find('input');
    TestUtils.Simulate.change(input, { target: { value: 'abcdefghijk' } });
    expect(result.state().value).to.equal("abcdefghij");
  });

那么如何模拟用户输入以便他们可以测试 onChange 功能?

您的输入组件中似乎有错误。当 event.target.value.length > this.props.maxLength 您从未设置实际状态时,将 state.value 保留为 ''。您似乎希望它已设置为该值,但被截断为 maxLength。您需要自己添加:

handleChange(event) {
  /* Check if max length has been set. If max length has been
  set make sure the user input is less than max Length, otherwise
  return before updating the text string. */
  if (this.props.maxLength) {
    if (event.target.value.length > this.props.maxLength) {
      // ** Truncate value to maxLength
      this.setState({ value: event.target.value.substr(0, this.props.maxLength) });
      return;
    }
  }
  this.setState({ value: event.target.value });
}

...然后,以下测试有效并通过:

it('Make sure inputted text is shorter than max length', () => {
  const result = mount(<Input maxLength={10}></Input>);
  result.find('input').simulate('change', { target: { value: '1234567890!!!' } });
  expect(result.state().value).to.equal("1234567890");
});