【问题标题】:Test a function that calls an API测试调用 API 的函数
【发布时间】:2017-02-20 18:52:35
【问题描述】:

我需要测试fetchData() 函数。在过去的 3 个小时里,我一直在尝试遵循 this(和许多其他)教程,并试图让它与我的功能一起工作,但到目前为止还没有运气。无论如何,我最好还是想用另一种方式来做,因为我认为 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>);

【问题讨论】:

  • 不确定测试部分,但您可能希望将“this”绑定到您的 fetchData 函数,因此其中的 this.setState 指的是 Home 组件。
  • edit: nvm 我已经有了它,我只是删除了几行来虚拟化组件。不过谢谢!
  • 嗯不确定它为什么起作用,但基本上,如果您在函数中引用 this,然后将其传递给另一个组件而不绑定“this”(在您的示例中为 SearchForm),“this”将在 SearchForm 中调用和更新状态时引用该组件,而不是 Home。在您的示例中,您对 onChange 事件使用箭头函数,该事件会自动将自身绑定到 Home 组件,因此 this.setState({value: e.target.value} 会正确更新您在 Home 组件中的状态。

标签: javascript reactjs testing axios


【解决方案1】:
  1. 要检查是否在提交表单时调用了该函数,您可以使用作为onSubmit 属性传递的spy 函数对&lt;SearchForm&gt; 组件进行浅渲染。模拟submit事件,检查spy函数是否被调用。
  2. 要检查数据是否返回,请模拟 axios 服务。您可以使用 this library 模拟 axios 调用。调用fetchData() 看看this.nodes 和状态是否更新正确。

    const wrapper = shallow(<Home />);
    wrapper.instance().fetchData().then(() => {
      ... your assertions go here ...
    })
    

我认为从发生异步操作的方法返回 Promise 对象或任何可链接的对象始终是最佳实践。

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 2022-01-19
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多