title: How to test a React asynchronous custom hook that returns a boolean when an API call is resolved/rejected
body: <p>I have a custom React hook as follows:</p>
  <pre><code>export function useValidPolicyReference({
    token,
    tenant,
    policyReference,
  }: UseValidPolicyReferenceProps): Record&lt;string, boolean&gt; {
    const [isValid, setIsValid] = React.useState&lt;boolean&gt;(true);
  
    React.useEffect(() =&gt; {
      async function fetchOnMount(): Promise&lt;void&gt; {
        try {
          await getPolicyByReference({
            policyReference: policyReference as string,
            tenant,
            token,
          });
        } catch (error) {
          setIsValid(false);
        }
      }
      if (tenant !== '' &amp;&amp; policyReference !== null &amp;&amp; token !== '') {
        fetchOnMount();
      }
    }, [policyReference, tenant, token]);
  
    return {
      isValidPolicyReference: isValid,
    };
  </code></pre>
  <p>I want to test that <code>isValidPolicyReference</code> will return true when <code>getPolicyByReference </code> does not throw and false when it does.</p>
  <p>My test for the true case is as follows:</p>
  <pre><code>  test('should be truthy if the policy reference is valid', () =&gt; {
      (getPolicyByReference as jest.Mock).mockImplementationOnce(() =&gt;
        Promise.resolve(true)
      );
      const {
        result: { current },
        waitForNextUpdate,
      } = render();
  
      expect(current.isValidPolicyReference).toBeTruthy();
  
      waitForNextUpdate();
  
      expect(getPolicyByReference).toHaveBeenCalledWith({
        token,
        tenant,
        policyReference,
      });
      expect(current.isValidPolicyReference).toBeTruthy();
    });
  </code></pre>
  <p>Which passes but the test for the false case does not:</p>
  <pre><code>  test('should be falsy if the policy reference is invalid', () =&gt; {
      (getPolicyByReference as jest.Mock).mockImplementationOnce(() =&gt;
        Promise.reject(new Error('policy reference error'))
      );
      const {
        result: { current },
        waitForNextUpdate,
      } = render();
  
      expect(current.isValidPolicyReference).toBeTruthy();
  
      waitForNextUpdate();
  
      expect(current.isValidPolicyReference).toBeFalsy();
    });
  </code></pre>
  <p>It fails on two counts:</p>
  <ol>
  <li>isValidPolicyReference never returns as false</li>
  <li>There is also a <code>console.error</code> logged at this line <code>setIsValid(false);</code> where <code>Warning: Can't perform a React state update on an unmounted component.</code></li>
  </ol>
  <p>I am not sure how to get <code>getPolicyByReference</code> to throw in Jest so that the hook will return the false value.</p>
  <p>What am I not doing correctly?  Should I be wrapping my test cases in <code>async</code> <code>await</code>?  Should I mock <code>axios.get</code> instead of <code>getPolicyByReference</code>?</p>