2017-08-04 63 views
0

我有以下簡稱反應成分單元測試反應與玩笑改變成分,酶

render() { 
     return (
      <div className={styles.srchBoxContaner}> 
       <input 
        className={styles.incSrchTextBox} 
        type="text" name="search" placeholder="Search.." 
        onChange={this.onChange} 
       /> 
      </div> 
     ); 
    } 

現在我想單元測試這一點,特別是我想模擬輸入並確認的onChange被稱爲

我該如何使用Enzyme和Jest來做到這一點。到目前爲止,這是我已經拿出

it('calls \'onPerformIncrementalSearch\' when the user types in something',() => { 
    const incrementalSearchWrapper = mount(<IncrementalSearch />); 

    const onChangeSpy = sinon.spy(IncrementalSearch.prototype, 'onChange'); 

    //find the input element 
    const searchInput = incrementalSearchWrapper.find('#search'); 
    searchInput.simulate('change', { target: { value: 'new search value' } }); 
    expect(IncrementalSearch.prototype.onChange.called).toEqual(true); 
    onChangeSpy.restore(); 
}); 

但是,這似乎並不奏效。

回答

0

爲防萬一有人遇到這個問題,修正是在調用mount之前移動間諜。所以工作代碼是

const onChangeSpy = sinon.spy(IncrementalSearch.prototype, 'onChange'); 
    const incrementalSearchWrapper = mount(<IncrementalSearch />); 

    //find the input element 
    const searchInput = incrementalSearchWrapper.find('#searchInput'); 
    searchInput.node.value = 'David'; 
    searchInput.simulate('change', searchInput); 
    expect(onChangeSpy.called).toEqual(true); 
    onChangeSpy.restore();