title: How to mock window.location.href with Jest in React?
body: <p>I'm testing functionality that is not supposed to run locally and need to mock <code>window.location.href</code>:</p>
  <pre class="lang-js prettyprint-override"><code>const usePageTracking = (): void =&gt; {
    const location = useLocation();
  
    useEffect(() =&gt; {
      if (!window.location.href.includes(&quot;localhost&quot;)) {
        ReactGA.initialize(&quot;UA-000000-01&quot;);
        ReactGA.pageview(window.location.pathname + window.location.search);
      }
    }, []);
  };
  </code></pre>
  <p>In my tests:</p>
  <pre class="lang-js prettyprint-override"><code>describe(&quot;usePageTracking&quot;, () =&gt; {
    it(&quot;initializes ReactGA&quot;, () =&gt; {
      render(&lt;Example /&gt;);
      expect(ReactGA.initialize).toHaveBeenCalled();
    });
  
    it(&quot;tracks page view&quot;, () =&gt; {
      render(&lt;Example /&gt;);
      expect(ReactGA.pageview).toHaveBeenCalledWith(&quot;/&quot;);
    });
  });
  </code></pre>
  <p>Note: there's a <a href="https://stackoverflow.com/questions/54021037/how-to-mock-window-location-href-with-jest-vuejs/63382670">related question around Vue</a> but it wasn't clear to me if the solutions apply to React as well (some just didn't work).</p>