2016-02-01 104 views
3

我使用Jest測試了React組件的表單輸入,但是我無法找到使用React TestUtils選擇表單輸入字段進行輸入的最佳方法。在線文檔顯示了一個使用refs的示例,但React文檔還聲明refs應僅用於父級而不是組件的子級。我應該將refs附加到每個輸入字段還是有更好的方式來遍歷DOM並選擇特定的元素,以便我可以模擬點擊事件?在React with Jest中測試模擬表單輸入

這是我的渲染

render (
    <form className="products"> 
     <input onChange={this.handleName} name="name" type="text" /> 
     <input onChange={this.hanndleAge} name="age" type="text" /> 
    </form> 
) 

和我的測試

it('Should parse input fields',() => { 
    Product = TestUtils.renderIntoDocument(<ProductComponent />); 

    // This returns all the inputs but how do tell them apart? 
    let inputs = TestUtils.scryRenderedDOMComponentsWithTag(Product, 'input'); 
}); 

回答

0

你不應該救裁判,如果你想使用它們的唯一原因是爲了能夠測試你的組件。

inputs變量是一個包含所有結果的常規數組,您可以通過索引獲得所需的結果。

it('Should parse input fields',() => { 
    Product = TestUtils.renderIntoDocument(<ProductComponent />); 

    // This returns all the inputs but how do tell them apart? 
    let inputs = TestUtils.scryRenderedDOMComponentsWithTag(Product, 'input'); 

    let firstInput = inputs[0]; 
    let secondInput = inputs[1]; 
}); 

您還可以使用常規瀏覽器API來遍歷DOM樹您隔離組件的主要的DOM元素之後(在你的情況下,它form):

it('Should parse input fields',() => { 
    Product = TestUtils.renderIntoDocument(<ProductComponent />); 

    let node = ReactDOM.findDOMNode(Product); 

    let firstInput = node.querySelector("[name=name]"); 
    let secondInput = node.querySelector("[name=age]"); 
});