如何使用FETCH设置单元测试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用FETCH设置单元测试相关的知识,希望对你有一定的参考价值。

我一直在尝试在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,
    })
  })

}

期待函数/方法此刻得到调用。实际结果将在稍后处理

答案

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

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();

这将只检查函数是否已被调用,无论结果如何。

以上是关于如何使用FETCH设置单元测试的主要内容,如果未能解决你的问题,请参考以下文章

如何在带有 Jest 的 react-native 中使用模拟的 fetch() 对 API 调用进行单元测试

单元测试很棒,但是

单元测试不了解 XCTest 期望的异步 UI 代码?

使用 Fetch Results Controller 对 Core Data 中的单元格重新排序

如何使用 IntentsTestRule 和 launchFragmentInContainer 测试从片段发送的意图

如何使用 Redux Tool Kit 的“createSlice”设置一个单元测试 Redux?