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

时间:2017-01-03 20:24:18

标签: javascript unit-testing reactjs jestjs enzyme

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

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建议使用酶的模拟变化,这可以在下面看到。但是,这只会返回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建议的react test utils,下面是我尝试过的代码,但是这个错误消息: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函数?

2 个答案:

答案 0 :(得分:8)

您的输入组件中似乎有错误。当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");
});

答案 1 :(得分:0)

尝试一下:

component = shallow(<Input value={'100.00'} />);


it('The component should display new value on the user input', () => {
        component.find(Input).simulate('change', { target: { value: '200.00' } });
        const input = component.find(Input);
        expect(input.prop('value')).not.toBe('100.00');
        expect(input.prop('value')).toBe('200.00');
      });