title: How to properly use Promises and Timers with Jest
body: <p>I have searched both SO and Google and found a lot of similar questions and answers, but none of them seems to have helped me solve my issue.</p>
  
  <p>I am attempting to write some test cases where I need to mock an async polling function. But no matter what I do I get:</p>
  
  <p><strong><em>Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout</em></strong></p>
  
  <p>I set up some minimal test cases the reproduce the problem:</p>
  
  <pre class="lang-js prettyprint-override"><code>jest.useFakeTimers();
  
  describe('timers test', () =&gt; {
    it('plain timer works as expected', () =&gt; {
      const mock = jest.fn();
      setTimeout(mock, 5000);
  
      jest.runAllTimers();
      expect(mock).toHaveBeenCalled();
    });
  
    it('Using a timer to mock a promise resolution results in a jest timeout error', async () =&gt; {
      const mock = jest.fn(() =&gt; {
        return new Promise((resolve) =&gt; setTimeout(resolve, 500));
      });
  
      const handler = jest.fn();
  
      await mock().then(handler);
  
      jest.runAllTimers();
  
      expect(handler).toHaveBeenCalled();
    });
  
    it('Using a timer to mock a promise rejection results in a jest timeout error', async () =&gt; {
      const mock = jest.fn(() =&gt; {
        return new Promise((resolve, reject) =&gt; setTimeout(reject, 500));
      });
  
      const handler = jest.fn();
  
      await mock().catch(handler);
  
      jest.runAllTimers();
  
      expect(handler).toHaveBeenCalled();
    });
  });
  </code></pre>
  
  <p>Can someone explain what I am doing wrong and why?</p>