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

时间:2020-08-23 07:41:23

标签: reactjs unit-testing react-testing-library

我需要将自定义钩子包装在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中调用函数的

0 个答案:

没有答案