React组件使用的Jest / Enzyme / Reactjs测试功能

时间:2019-01-07 19:42:57

标签: reactjs jestjs enzyme

嗨,我有这个函数(apiCall),它可以在组件内部调用API,并使用数据来更新状态(然后使用chartjs渲染图表)。我想专门测试componentDidMount内部的过程,该过程无需调用API即可更新状态。在花了很多时间寻找一种模拟方法之后,我仍然无法弄清楚。尝试通过模拟apiCall函数声明更改后的状态。

这是apiCall函数:

const apiCall = (uri) => {
    return fetch(uri)
      .then( (res) => {
         return res
      })
      .catch( (ex) => {
         return 0
      })
 }

 export default apiCall;

// and this is the componentDidMount

componentDidMount() {
      apiCall(this.props.uri)
      .then((result) => result.json())
      .then((result) => {
        this.setState({ data: result });
      })
      this.setState({ legend: this.props.legend })
  }

2 个答案:

答案 0 :(得分:0)

其中一种选择是使用fetch-mock

http://www.wheresrhys.co.uk/fetch-mock/

答案 1 :(得分:0)

使用proxyquire和模拟承诺功能