title: Jest: Test for promise that rejects after timeout
body: <p>I'm trying to write a test for the sad path of this function:</p>
  <pre class="lang-js prettyprint-override"><code>const awaitFirstStreamForPage = async page =&gt; {
    try {
      await page.waitForSelector('[data-stream=&quot;true&quot;]', {
        timeout: MAX_DELAY_UNTIL_FIRST_STREAM,
      })
    } catch (e) {
      throw new Error(`no stream found for ${MAX_DELAY_UNTIL_FIRST_STREAM}ms`)
    }
  }
  </code></pre>
  <p>I managed to write a test that passes, but it takes 10 seconds to run because it actually waits for the test to finish.</p>
  <pre class="lang-js prettyprint-override"><code>describe('awaitFirstStreamForPage()', () =&gt; {
    it('given a page and no active stream appearing: should throw', async () =&gt; {
      jest.setTimeout(15000)
  
      const browser = await puppeteer.launch({ headless: true })
      const page = await getPage(browser)
  
      let error
  
      try {
        await awaitFirstStreamForPage(page)
      } catch (err) {
        error = err
      }
  
      const actual = error.message
      const expected = 'no stream found for 10000ms'
  
      expect(actual).toEqual(expected)
  
      await browser.close()
      jest.setTimeout(5000)
    })
  })
  </code></pre>
  <p>There is probably a way to solve it using Jest's fake timers, but I couldn't get it to work. Here is my best attempt:</p>
  <pre class="lang-js prettyprint-override"><code>const flushPromises = () =&gt; new Promise(res =&gt; process.nextTick(res))
  
  describe('awaitFirstStreamForPage()', () =&gt; {
    it('given a page and no active stream appearing: should throw', async () =&gt; {
      jest.useFakeTimers()
  
      const browser = await puppeteer.launch({ headless: true })
      const page = await getPage(browser)
  
      let error
  
      try {
        awaitFirstStreamForPage(page)
        jest.advanceTimersByTime(10000)
        await flushPromises()
      } catch (err) {
        error = err
      }
  
      const actual = error.message
      const expected = 'no stream found for 10000ms'
  
      expect(actual).toEqual(expected)
  
      await browser.close()
      jest.useRealTimers()
    })
  })
  </code></pre>
  <p>which fails and throws with</p>
  <pre><code>(node:9697) UnhandledPromiseRejectionWarning: Error: no stream found for 10000ms
  </code></pre>
  <p>Even though I wrapped the failing function in a <code>try/catch</code>. How do you test a function like this using fake timers?</p>