title: ref from useRef is null from Jest & react-testing-library unit test
body: <p>I have the following component, where I create ref on nav to close the menu on click outside of nav:</p>
  <pre class="lang-js prettyprint-override"><code>import { useState, useEffect, useRef, } from 'react';
  
  const Header = () =&gt; {
    const [menuOpen, setMenuOpen] = useState(false);
    const navRef = useRef(null);
  
    const hideMenu = () =&gt; setMenuOpen(false);
  
    const handleClick = event =&gt; {
      if (menuOpen &amp;&amp; !navRef.current.contains(event.target)) {
        hideMenu();
      }
    };
  
    useEffect(() =&gt; {
      document.addEventListener('click', handleClick);
      return () =&gt; {
        document.removeEventListener('click', handleClick);
      };
    });
  
    return (
      &lt;header className=&quot;header&quot;&gt;
        &lt;nav className=&quot;header-nav&quot; ref={navRef}&gt;
          ...
        &lt;/nav&gt;
      &lt;/header&gt;
    );
  };
  
  export default Header;
  </code></pre>
  <p>And this is the unit test:</p>
  <pre class="lang-js prettyprint-override"><code>import React from 'react';
  
  import '@testing-library/jest-dom';
  import { cleanup, fireEvent } from '@testing-library/react';
  import renderer from 'react-test-renderer';
  
  import Header from './Header';
  const { act } = renderer;
  
  afterEach(cleanup);
  
  describe('Header', () =&gt; {
    test('should open and close mobile menu', () =&gt; {
      const headerComponent = renderer.create(&lt;Header /&gt;);
      const headerRoot = headerComponent.root;
      const navContainer = headerRoot.findByType('nav');
  
      act(() =&gt; {
        // open menu
        navContainer.children[0].props.onClick(new MouseEvent('click'));
      });
      act(() =&gt; {
        // click on document
        fireEvent(document, new MouseEvent('click'));
      });
      headerTree = headerComponent.toJSON();
      expect(headerTree).toMatchSnapshot();
    });
  });
  </code></pre>
  <p>The test run results in the following error:</p>
  <pre><code>    TypeError: Cannot read property 'contains' of null
  
        26 |
        27 |   const handleClick = (event) =&gt; {
      &gt; 28 |     if (menuOpen &amp;&amp; !navRef.current.contains(event.target)) {
           |                                     ^
        29 |       hideMenu();
        30 |     }
        31 |   };
  </code></pre>
  <p>I have tried to mock <code>ref.currrent</code> but it's still <code>null</code>:</p>
  <pre><code>jest.spyOn(React, 'useRef').mockReturnValue({
    current: navContainer,
  });
  </code></pre>
  <p>Please advice how I can organize the test to be able to test this</p>
  <p>P.S. I have found this answer but it doesn't suit me as I don't wanna pass ref as a prop: <a href="https://stackoverflow.com/a/59207195/3132457">https://stackoverflow.com/a/59207195/3132457</a></p>