Home > database >  Cannot read property 'displayName' of undefined. React Jest Enzyme
Cannot read property 'displayName' of undefined. React Jest Enzyme

Time:04-28

I am rendering a react Component App.tsx which uses useEffect hook. Inside the useEffect, it makes an async call updates the state delivery defined in App.tsx. At first render, delivery is undefined, but after next re-render, it is defined.

const App = () => {
  const [delivery, setDelivery] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setup()
  }, [])

  const setup = async () => {
    try {
      const response = await someAsyncCall()
      setDelivery(response)    
      setLoading(true)
    /// Other functionality
    } catch (err) {
      console.log(err)
    }finally{
        setLoading(false)
    }
    
  }
  return (
      <>
      {loading? <div>Loading!!</div>
        : <div>App has loaded with {delivery.displayName} {delivery.id}</div>  
    }
      </>
  )
}

How to write unit test so that it re-renders with right value? Right now I get Uncaught [TypeError: Cannot read property 'displayName' of undefined]

Unit Test I wrote :

describe('test', ()=>{
    it("mounts", ()=>{
       const wrapper =  mount(<App />)
    })
})

Any thoughts on how to re-render? I read wrapper.update() could be used. I was wondering how?

CodePudding user response:

Shouldn't this solve the problem?

return (
  <>
    {loading || !delivery ? <div>Loading!!</div>
      : <div>App has loaded with {delivery.displayName} {delivery.id}</div>  
        }
  </>
)
  • Related