4
我需要測試fetchData()
函數。我一直在嘗試遵循this(以及其他許多)教程,並試圖讓它在過去的3個小時內與我的功能一起工作,但目前爲止還沒有運氣。我最好還是想以另一種方式來做,因爲我不認爲jQuery和React應該一起使用。測試調用API的函數
我基本上想檢查是否1)當提交搜索表單(SearchForm中的按鈕被點擊)時調用該函數並且2)檢查數據是否返回。
有沒有人有關於如何開始的建議?
感謝
首頁
export default class Home extends Component {
constructor() {
super();
this.state = {
value: '',
loading: false,
dataError: false
}
this.nodes = [];
this.fetchData = this.fetchData.bind(this);
}
fetchData(e) {
e.preventDefault();
this.setState({loading: true});
axios.get(`https://api.github.com/search/repositories?q=${this.state.value}`)
.then(res => {
this.nodes = res.data.items.map((d, k) => <RepoItem {...d} key={k}/>);
this.setState({loading: false});
})
.catch(err => {
this.setState({dataError: true});
});
}
render() {
return (
<div className="home-wrapper">
<SearchForm value={this.state.value}
onSubmit={this.fetchData}
onChange={(e) => this.setState({value: e.target.value})}/>
{this.state.loading ?
<Spinner/>:
!this.state.dataError ? this.nodes :
<h1>Oops! Something went wrong, please try again!</h1>}
</div>
);
}
}
RepoItem
export const RepoItem = props => (
<div className="repo-item">
<h1>{props.full_name}</h1>
</div>);
不確定測試部分,但您可能想要將'this'綁定到您的fetchData函數,所以其中的this.setState引用Home部件。 – Mateusz
編輯:nvm我已經擁有了它,我只是刪除了一些虛擬的組件。雖然謝謝! – Apswak
嗯不知道爲什麼它的作品,但基本上,如果你在你的函數中引用它,然後將它傳遞給另一個組件,而不綁定'this'(在你的例子中是SearchForm),'this'將在調用時引用該組件,在SearchForm中更新狀態,而不是Home。在你的例子中,你可以使用onChange事件的箭頭函數來自動綁定到Home組件,所以this.setState({value:e.target.value}正確地更新你的Home組件的狀態。 – Mateusz