2014-11-06 10 views
12

Ho i seguenti componenti React e voglio selezionare uno degli elementi di selezione nel mio select-block con TestUtils. Come lo faccio?Seleziona l'opzione con React TestUtils Simula

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

Ho già provato a farlo in questo modo:

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

ma non dovesse funzionare.

risposta

13

Il problema potrebbe essere che Simulate.change chiama solo la funzione di modifica della selezione (che non esiste). Non penso che in realtà causerà la modifica del valore della selezione a meno che non si provochi tale modifica nel gestore onChange.

Se ti ostini a usare refs sopra onChange, modificare questa linea:

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

a questo:

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

Quale sarebbe il modo appropriato per testare questo allora? –

+2

Con refs o con valore/onChange? – FakeRainBrigand