title: React hooks/Jest/Enzyme Test useEffect, which adds and removes event listeners on ref
body: <p>I have the following component:</p>
  <pre><code>export const DeviceModule = (props: Props) =&gt; {
    const [isTooltipVisible, changeTooltipVisibility] = useState(false)
    const deviceRef = useRef(null)
    useEffect(() =&gt; {
      if (deviceRef &amp;&amp; deviceRef.current) {
        deviceRef.current.addEventListener(EVENT_TYPE.MOUSEOVER, () =&gt; changeTooltipVisibility(true))
        deviceRef.current.addEventListener(EVENT_TYPE.MOUSEOUT, () =&gt; changeTooltipVisibility(false))
      }
      return () =&gt; {
        deviceRef.current.removeEventListener(EVENT_TYPE.MOUSEOVER, () =&gt; changeTooltipVisibility(true))
        deviceRef.current.removeEventListener(EVENT_TYPE.MOUSEOUT, () =&gt; changeTooltipVisibility(false))
      }
    })
  
    return (
      // some jsx. When you hover on a div, it triggers one of the event listeners and changes the state. 
    )
  }
  </code></pre>
  <p>How should I test it using Jest and Enzyme?</p>
  <p><strong>UPDATE 2021. Do not use enzyme!</strong></p>
  <p>The whole story is explained thoroughly <a href="https://www.piotrstaniow.pl/goodbye-enzyme" rel="nofollow noreferrer">here</a>.
  In short:</p>
  <ol>
  <li>AirBNB(they created it) stopped supporting it and instead gave it to someone else and right now only one person is taking care of it.</li>
  <li>It has not been updated for 2 years, which means it does not support react 17(react 18 is right around the corner by the way). There are 3rd party adapters for react 17, but each of them has its issues and it faces the same problem of depending on a project, which has no guarantee of being supported.</li>
  <li>Functional components(like the one in the question) are hard to make, because enzyme was not intended for them.</li>
  <li>Enzyme uses some internal react features, which is discouraged and could create even worse problems if react changes.</li>
  <li>Jest has moved a couple of version up, using different environment, which further complicates things.</li>
  </ol>
  <p>The industry standard right now is <a href="https://testing-library.com/docs/react-testing-library" rel="nofollow noreferrer">react-testing-library</a> It is also recommended  by the react team, who stopped using enzyme as well.</p>