profile
viewpoint

Ask questionsTypeError: Cannot read property 'body' of null

This method:

https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/client/getActiveElement.js

Is throwing this error in jest:

image

I realize that this method is checking only when the document is undefined. However, using jest looks that is setting sometimes the document to null, causing this error.

To reproduce it, I'm testing a callback that is using an async task:

 const asyncTask = useCallback(async (data) => {
    dispatch({ type: 'FETCH' })

    try {
      const res = await MyService.asyncMethod(data)
      dispatch({ type: 'SUCCESS', data: res })
    } catch (e) {
      dispatch({ type: 'ERROR' }) // This dispatch throw this error in jest
    }
  }, [])

About the test, I'm just mocking the service and testing the different scenarios.

I imagine that is related that the dispatch from the useReducer, that it's used inside the catch, is fired when the component maybe is unmount? @gaearon In this case how can I do a safer dispatch inside a callback method?

facebook/react

Answer questions aralroca

I tried to do this:

 const dispatchSafe = useSafeDispatch(dispatch)

 const asyncTask = useCallback(async (data) => {
    dispatchSafe({ type: 'FETCH' })

    try {
      const res = await MyService.asyncMethod(data)
      dispatchSafe({ type: 'SUCCESS', data: res })
    } catch (e) {
      dispatchSafe({ type: 'ERROR' }) // This dispatchSafe throw the error in jest
    }
  }, [])

When useSafeDispatch is:

export default function useSafeDispatch(dispatch) {
  const dispatchSafe = useRef(dispatch)

  useEffect(() => () => {
    dispatchSafe.current = () => null
  }, [])

  return dispatchSafe.current
}

However, this doesn't solve the problem. Maybe I'm doing something wrong?

useful!
source:https://uonfu.com/
answerer
Aral Roca Gomez aralroca Vinissimus Barcelona https://aralroca.com Currently working at @vinissimus as Senior Software Engineer
Github User Rank List