Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai
<p>So, I'm testing a component that relies on an event-emitter. To do so I came up with a solution using Promises with Mocha+Chai:</p>
<pre><code>it('should transition with the correct event', (done) =&gt; {
  const cFSM = new CharacterFSM({}, emitter, transitions);
  let timeout = null;
  let resolved = false;
  new Promise((resolve, reject) =&gt; {
    emitter.once('action', resolve);
    emitter.emit('done', {});
    timeout = setTimeout(() =&gt; {
      if (!resolved) {
        reject('Timedout!');
      }
      clearTimeout(timeout);
    }, 100);
  }).then((state) =&gt; {
    resolved = true;
    assert(state.action === 'DONE', 'should change state');
    done();
  }).catch((error) =&gt; {
    assert.isNotOk(error,'Promise error');
    done();
  });
});
</code></pre>
<p>On the console I'm getting an 'UnhandledPromiseRejectionWarning' even though the reject function is getting called since it instantly shows the message 'AssertionError: Promise error'</p>
<blockquote>
<p>(node:25754) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id:  2): AssertionError: Promise error: expected
{ Object (message, showDiff, ...) } to be falsy</p>
<ol>
<li>should transition with the correct event</li>
</ol>
</blockquote>
<p>And then, after 2 sec I get</p>
<blockquote>
<p>Error: timeout of 2000ms exceeded. Ensure the done() callback is
being called in this test.</p>
</blockquote>
<p>Which is even weirder since the catch callback was executed(I think that for some reason the assert failure prevented the rest of the execution)</p>
<p>Now the funny thing, if I comment out the <code>assert.isNotOk(error...)</code> the test runs fine without any warning in the console. It stills 'fails' in the sense that it executes the catch.<br />
But still, I can't understand these errors with promise. Can someone enlighten me?</p>