使用React TestUtils模拟选择选项

12

我有以下的React组件,我想使用TestUtils在我的select-block中选择其中一个selectElements。我该怎么做?

var selectElements = ["type_a", "type_b"];

var SelectElement = React.createClass({
  render: function() {
    return (
      <option value={this.props.type}>{this.props.type}</option>
      );
  }
});

var MyForm = React.createClass({
  handleSubmit: function(e) {
    console.log("submitted");
  },
  render: function () {
    var selectElements = this.props.availableTypes.map(function (type) {
      return (
        <SelectElement key={type} type={type} />
        );
    });
    return (
      <form role="form" onSubmit={this.handleSubmit}>
        <select ref="type" name="type">
          <option value="">-- Choose --</option>
          {selectElements}
        </select>
        <input type="submit" value="Search"/>
      </form>
      );
  }
});

我已经尝试过这样做了:

var myFormComponent = TestUtils.renderIntoDocument(<MyForm selectElements={selectElements} />);
var form = TestUtils.findRenderedDOMComponentWithTag(myFormComponent, 'form');
var selectComponent = TestUtils.findRenderedDOMComponentWithTag(form, 'select');

TestUtils.Simulate.change(selectComponent, { target: { value: 'type_a' } });
TestUtils.Simulate.submit(form);

但它不起作用。

1个回答

13

问题可能在于Simulate.change仅调用了select的onChange(但该函数并不存在)。我认为这不会导致select的值发生变化,除非您在onChange处理程序中引起该变化。

如果您坚持使用refs而不是onChange,请更改此行:

TestUtils.Simulate.change(selectComponent, { target: { value: 'type_a' } });

变成这样:

selectComponent.getDOMNode().value = 'type_a';

那么测试这个的适当方式是什么? - Johnny Everson
2
使用 refs 还是 value/onChange? - Brigand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接