Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read property 'displayName' of undefined. React+Jest+Enzyme

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Shouldn’t this solve the problem?

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading