javascript - 测试调用 API 的函数

标签 javascript reactjs testing axios

我需要测试 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>);

最佳答案

  1. 要检查函数是否在表单提交时被调用,您可以浅渲染 <SearchForm>组件与 spy作为 onSubmit 传递的函数支柱。模拟 submit事件并检查是否 spy函数被调用。
  2. 要检查数据是否返回,模拟 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/

相关文章:

c# - NUnit 的奇怪行为,ExpectedException & yield return

Java测试驱动开发

javascript - 在 Protractor 测试中获取和使用属性

javascript - document.querySelector 获取包含括号的类名

javascript - 如何映射 JavaScript 数组的 i 和 i+1 值?

reactjs - Redux-thunk 输入的默认值

javascript - 如果 eslint 未验证,如何配置 Parcel 以退出构建并出现错误

javascript - jQuery - 检测使用 .val() 函数的值变化

reactjs - 为什么将 Electron 与 SPA 框架结合使用?

python - 后台进程的 cy.exec 超时