title: Jest - test for React memory leak
body: <p>I have a component with a promise. I want that promise to be cancelled on unmounting (I use Bluebird to cancel the promise). I just don't know how to test that. Is there a way to test for that using Jest? I guess I can mock the promise, but I would prefer if there was a better way. Is there a way to change the warning <code>Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.</code> to be an error so I can use an <code>expect(...).not.toThrow();</code>.</p>
  <p>This is an App.js example (here I use a timeout instead of a promise):</p>
  <pre><code>import {useRef, useState} from &quot;react&quot;;
  
  function App() {
      const curTimeout = useRef(setTimeout(()=&gt;{}, 0));
      const [state, setState] = useState();
  
      function setNewTimeout() {
          clearTimeout(curTimeout.current);
  
          curTimeout.current = setTimeout(()=&gt;{
              setState(1);
          }, 1000);
      }
  
      return (
          &lt;button onClick={setNewTimeout}&gt;
              CLICK ME
          &lt;/button&gt;
      );
  }
  
  export default App;
  </code></pre>
  <p>Here is my App.test.js code:</p>
  <pre><code>import {act, fireEvent, render} from &quot;@testing-library/react&quot;;
  import App from &quot;./App&quot;;
  
  beforeEach(() =&gt; {
    jest.useFakeTimers();
  });
  
  test(&quot;test for memory leaks&quot;, async () =&gt; {
    const {unmount, getByText} = render(&lt;App /&gt;);
  
    fireEvent.click(getByText(&quot;CLICK ME&quot;));
    unmount();
  
    act(()=&gt;{
      jest.runAllTimers();
    });
  });
  </code></pre>
  <p>The app was created with create-react-app. When I add</p>
  <pre><code>useEffect(() =&gt; {
          return () =&gt; {
              clearTimeout(curTimeout.current);
          };
      }, []);
  </code></pre>
  <p>the test should now work.</p>