Search code examples
reactjsreactjs-testutils

Select option with React TestUtils Simulate


I have the following React components, and I want to select one of the selectElements in my select-block with TestUtils. How do I do that?

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

I've already tried doing it like this:

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);

but it doesn't work.


Solution

  • The problem might be that Simulate.change only calls the select's onChange (which doesn't exist). I don't think it'll actually cause the select's value to change unless you cause that change in your onChange handler.

    If you insist on using refs over onChange, change this line:

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

    to this:

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