如何使用FETCH设置单元测试

时间:2018-12-19 17:57:20

标签: javascript reactjs unit-testing

我一直在尝试为以下代码在VSC-JS / React上设置单元测试。

getNotificationgetNotificationCount = () =>{
fetch(`${this.state.services.NotificationReporting.URL}/NOTIFICATIONS?$count=true&$filter=contains(Notified,'${this.state.user.Email}') and Status eq 'Unread'`, {
  headers: {
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': this.state.services.NotificationReporting.subscription_key,
    "DDHFirm": this.state.user.DDHFirm
  },
  method: 'GET',
  credentials: 'include',
})
.then(res => {return(validationManager.ResolveHTTPResponse(res, 'Request Successful', 'Request Failed', res.ok ? true : false))})
  .then(response => {
    this.setState({
      unreadNotifications: response.body ? response.body['@odata.count'] : 0,
    })
  })

}

期望函数/方法被调用。实际结果将在以后处理

1 个答案:

答案 0 :(得分:1)

您可以在函数中设置间谍以检查其是否已被调用:

const spy = jest.spyOn(Component.prototype, 'getNotificationgetNotificationCount');
const wrapper = mount(<Component {...props} />);
// Next line will call the function, replace it with
// any code that will trigger the call
wrapper.instance().getNotificationgetNotificationCount();
expect(spy).toHaveBeenCalled();

这将仅检查是否已调用该函数,而不管结果如何。