title: Mocking GeoLocation API Hook In React
body: <p>I currently have the following custom hook to access the geolocation API:</p>
  <pre><code>const useGeoLocAPI = () =&gt; {
    const [coords, setCoords] = useState(null);
    if (&quot;geolocation&quot; in navigator) {
      navigator.geolocation.getCurrentPosition(
        (position) =&gt; {
          setCoords({
            lat: position.coords.latitude,
            long: position.coords.longitude,
          });
        },
        (error) =&gt; {
          console.error(error.message);
        }
      );
    }
    return [coords, setCoords];
  };
  
  export default useGeoLocAPI;
  </code></pre>
  <p>Since the success callback uses setState , i'm having a hard time trying to mock this hook for testing. I've also heard mocking <code>setState</code> is an anti-pattern, which makes me wonder how I would even do this. I am able to do a simple smoke test by creating the following mock in my setupTests.js</p>
  <pre><code>const mockGeolocation = {
    getCurrentPosition: jest.fn(),
    watchPosition: jest.fn(),
  };
  
  global.navigator.geolocation = mockGeolocation;
  </code></pre>
  <p>But because this mock doesn't setState, the hook always returns <code>null</code> in my tests.</p>
  <p>Is there a way to properly mock the geolocation API so I can do the following:</p>
  <ul>
  <li>Assert the shape of the state.</li>
  <li>Assert it's error handling</li>
  <li>Assert that it can actually set state</li>
  </ul>
  <p>I've created an <a href="https://github.com/mdwiltfong/reactive-weather-app/issues/7" rel="nofollow noreferrer">issue</a> of this in the project's repo in case more information is needed.</p>