使用React TestUtils Simulate选择选项

and*_*sem 12 reactjs reactjs-testutils

我有以下React组件,我想在我的select-block中选择一个带有TestUtils的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>
      );
  }
});
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这样做了:

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);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

Bri*_*and 13

问题可能是Simulate.change只调用select的onChange(它不存在).除非你在onChange处理程序中导致更改,否则我认为它实际上不会导致select的值发生变化.

如果您坚持在onChange上使用refs,请更改以下行:

TestUtils.Simulate.change(selectComponent, { target: { value: 'type_a' } });
Run Code Online (Sandbox Code Playgroud)

对此:

selectComponent.getDOMNode().value = 'type_a';
Run Code Online (Sandbox Code Playgroud)

  • 使用refs或value/onChange? (2认同)