Select option with React TestUtils Simulate
Asked Answered
R

1

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.

Ratchford answered 6/11, 2014 at 12:14 Comment(0)
Y
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';
Ywis answered 6/11, 2014 at 16:26 Comment(2)
What would be the appropriate way to test this then?Eulogist
With refs or with value/onChange?Ywis

© 2022 - 2024 — McMap. All rights reserved.