2016-12-30 26 views
0

我在我的一個小型測試項目中有一個簡單的SearchBar組件。 此SearchBar主要包含一個文本輸入和一個按鈕,其中按鈕單擊使用輸入字段中的文本執行回調。測試文字與反應和笑話輸入

Searchbar.render方法是這樣的:

it("should adjust keywords and trigger onSearch correctly",() => { 
    const handleSearch = jest.fn(); 

    const searchBar = ReactTestUtils.renderIntoDocument(
    <Searchbar onSearch={handleSearch}/> 
); 
    expect(searchBar.state.keywords).toBe(""); 

    const button = ReactDOM.findDOMNode(searchBar.refs.searchButton); 
    const input = ReactDOM.findDOMNode(searchBar.refs.searchInput); 

    ReactTestUtils.Simulate.change(input, {target: {value: "test"}}); 

    ReactTestUtils.Simulate.click(button); 
    expect(handleSearch).toHaveBeenCalledWith("test"); 
}); 

現在存儲在callMe在本次測試工作的回調函數得到的:

return (
    <FormGroup controlId="keywords"> 
     <InputGroup> 
     <FormControl type="text" 
        placeholder="Keywords…" 
        value={this.state.keywords} 
        onChange={this.updateKeywords} /> 
     <InputGroup.Button 
      onClick={() => {this.props.onSearch(this.state.keywords);}} 
      ref="searchInput"> 
      <Button ref="searchButton"> 
      <Glyphicon glyph="search"/> 
      </Button> 
     </InputGroup.Button> 
     </InputGroup> 
    </FormGroup> 
); 

我用開玩笑寫了一個test它稱爲預期。 SearchBar也適用於我的應用程序,所以我認爲SearchBar代碼是正確的。但是當我使用npm test運行我的測試的測試失敗:

expect(jest.fn()).toHaveBeenCalledWith(expected) 

Expected mock function to have been called with: 
    ["test"] 
But it was called with: 
    [""] 

在評論Andreas Köberle向我指出的是,updateKeywords方法似乎不能稱之爲問題應該是爲失敗的測試的原因。可悲的是我不明白爲什麼這個方法在測試中沒有被調用。

回答

1

您必須自行傳遞事件數據,因爲它並不真正觸發DOM元素上的事件。從文檔:

你必須提供你使用在你 組件(例如鍵代碼,其中,等...)的反應,你不創造任何這些 任何事件屬性。

將一個間諜函數作爲回調放入您的組件中也很常見,並且在模擬事件之後對其進行測試。

const handleSearch = jest.fn(); 
const searchBar = ReactTestUtils.renderIntoDocument(
    <Searchbar onSearch={handleSearch}/> 
); 
ReactTestUtils.Simulate.change(input, {target: {value: 'test'}}); 
expect(handleSearch).toHaveBeenCalledWith('test') 
+0

感謝您的指針!可悲的是,它迄今爲止並不奏效。 我調整了我的[Searchbar.test.js](https://github.com/runjak/spreadshirtRemoteTask/blob/master/src/Searchbar.test.js#L27),但'npm test'仍然抱怨。我調整了我的'master'分支,希望能夠更容易地重現。 –

+0

已更新我的回答,以顯示如何正確使用間諜。 –

+0

不錯,我不知道'toHaveBeenCalledWith'方法。這更優雅,但我的測試仍然失敗。我已經更新了相應的問題和主分支。 –