12

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.

1 Answer 1

13

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';
Sign up to request clarification or add additional context in comments.

2 Comments

What would be the appropriate way to test this then?
With refs or with value/onChange?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.