0

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.

fearless_fool
  • 33,645
  • 23
  • 135
  • 217

1 Answers1

0

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

Slava Shpitalny
  • 3,965
  • 2
  • 15
  • 22
  • Can you elaborate a little bit? I get the idea behind the library but I'm not sure how to apply it. In my case the promise is returned by the subject under test. If I mock what the subject under test returns then I can't really test it. –  Mar 24 '16 at 16:01
  • How does he create the Promise? You can mock the Promise factory, if you use the Q to defer a promise you can mock that – Slava Shpitalny Mar 24 '16 at 16:32
  • Got it - that's much better than my approach, thanks. –  Mar 24 '16 at 16:40