Search code examples
javascripttestingpromisemocha.jschai-as-promised

How can I test that a Promise is never fulfilled?


I'm testing a library I wrote to throttle execution of a function.

The API is throttler.do(fn) and it returns a promise of fn's return value (resolved at whichever point the throttler decides it's ok to run it).

I'm using lolex to fake Date() and setTimeout so if I set the throttler to allow two actions per minute and do

throttler.do(() => {});
throttler.do(() => {});
throttler.do(() => {}).should.eventually.equal(5);

this fails as expected (it times out because it's waiting on the last promise forever since I never call lolex.tick).

Is there a way I can turn this into a passing test, something like

throttler.do(() => {}).should.never.be.fulfilled;

I can't do

setTimeout(() => done(), 1500)

because the setTimeout method is faked by lolex.


Solution

  • You can mock the Promise to be synchronous and then check the Promise state. Here is a library you can use promise-sync