我需要测试 fetchData()
函数。我一直在努力关注this (和许多其他)教程,并在过去 3 小时内尝试让它与我的功能一起使用,但到目前为止运气不佳。无论如何,我最好想用另一种方式来做,因为我认为 jQuery 和 React 不应该一起使用。
我基本上想检查 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>
);
}
}
报告项
export const RepoItem = props => (
<div className="repo-item">
<h1>{props.full_name}</h1>
</div>);
最佳答案
- 要检查函数是否在表单提交时被调用,您可以浅渲染
<SearchForm>
组件与spy
作为onSubmit
传递的函数支柱。模拟submit
事件并检查是否spy
函数被调用。 要检查数据是否返回,模拟 axios 服务。您可以使用 this library模拟 axios 调用。调用
fetchData()
并查看this.nodes
并正确更新状态。const wrapper = shallow(<Home />); wrapper.instance().fetchData().then(() => { ... your assertions go here ... })
我认为返回 Promise
始终是最佳实践对象或来自发生异步操作的方法的任何可链接对象。
关于javascript - 测试调用 API 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352235/