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
方法似乎不能稱之爲問題應該是爲失敗的測試的原因。可悲的是我不明白爲什麼這個方法在測試中沒有被調用。
感謝您的指針!可悲的是,它迄今爲止並不奏效。 我調整了我的[Searchbar.test.js](https://github.com/runjak/spreadshirtRemoteTask/blob/master/src/Searchbar.test.js#L27),但'npm test'仍然抱怨。我調整了我的'master'分支,希望能夠更容易地重現。 –
已更新我的回答,以顯示如何正確使用間諜。 –
不錯,我不知道'toHaveBeenCalledWith'方法。這更優雅,但我的測試仍然失敗。我已經更新了相應的問題和主分支。 –