如何测试使用上下文的React自定义钩子?

问题描述

我需要将自定义钩子包装在TaskContext中,以便测试通过。当前,它们以“无法读取未定义的属性'taskState'的未定义”失败。taskState表示TaskContext中的状态对象。我尝试将钩子包装在下面的代码中,但测试仍然失败。

我的自定义钩子称为useProtocolEdit。我使用另一个名为mountHook的钩子进行测试。在添加TaskContext之前,所有测试都通过了。

  it("edit question",() => {
   let setupComponent = mountHook(useProtocolEdit)
   let hook = setupComponent.componentHook;
   let currentProtocol = {name: 'one'}
   let protocolId = 'some id'
   hook.editState.currentProtocol = currentProtocol

   act(() => {
     return (
       <TaskContext.Provider value={{ taskState: {tasks: null} }}>
         {hook.editactions.editProtocol(currentProtocol,protocolId)}
       </TaskContext.Provider>
     )
   })
   expect(hook.editState.isEdit).toBe(true)
   expect(hook.editState.protocolId).toBe('some id')
   expect(hook.editState.currentProtocol).toBe(currentProtocol)
 })

我的自定义钩子代码

  const useProtocolEdit = () => {
    const [editState,setEditState] = useState(INITIAL_STATE)
    const {index,protocolId,currentProtocol} = editState
    const {taskActions} = useTask()  

 const editProtocol = (currentProtocol,protocolId) => {
   setEditState({
     ...editState,isEdit: true,protocolId: protocolId,currentProtocol: currentProtocol
   })
 }

 const updateProtocol = (body,file = null) => {
   let updateProtocol = currentProtocol
   let updatedAnswers = updateProtocol.answeredQuestions
       updatedAnswers.splice(index,1,...body.answeredQuestions)

   body._id = protocolId
   body.answeredQuestions = updatedAnswers

   protocolService.update(body).then(res => {
     if (file) {
       protocolPhoto(res,file)
     }

     else {  
       taskActions.replaceTask(res)
       close()
     }
   })
 }

 const editactions = {
   editProtocol
 }

 return {editState,editactions} 

}

useTask是我用来在taskActions中调用函数

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)