RateLimitedQueue.test.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const RateLimitedQueue = require('./RateLimitedQueue')
  2. const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
  3. describe('RateLimitedQueue', () => {
  4. let pending = 0
  5. function fn () {
  6. pending++
  7. return delay(15).then(() => pending--)
  8. }
  9. it('should run at most N promises at the same time', async () => {
  10. const queue = new RateLimitedQueue(4)
  11. const fn2 = queue.wrapPromiseFunction(fn)
  12. const result = Promise.all([
  13. fn2(), fn2(), fn2(), fn2(),
  14. fn2(), fn2(), fn2(), fn2(),
  15. fn2(), fn2()
  16. ])
  17. expect(pending).toBe(4)
  18. await delay(10)
  19. expect(pending).toBe(4)
  20. await result
  21. expect(pending).toBe(0)
  22. })
  23. it('should accept Infinity as limit', () => {
  24. const queue = new RateLimitedQueue(Infinity)
  25. const fn2 = queue.wrapPromiseFunction(fn)
  26. const result = Promise.all([
  27. fn2(), fn2(), fn2(), fn2(),
  28. fn2(), fn2(), fn2(), fn2(),
  29. fn2(), fn2()
  30. ])
  31. expect(pending).toBe(10)
  32. return result.then(() => {
  33. expect(pending).toBe(0)
  34. })
  35. })
  36. it('should accept non-promise function in wrapPromiseFunction()', () => {
  37. const queue = new RateLimitedQueue(1)
  38. function syncFn () { return 1 }
  39. const fn2 = queue.wrapPromiseFunction(syncFn)
  40. return Promise.all([
  41. fn2(), fn2(), fn2(), fn2(),
  42. fn2(), fn2(), fn2(), fn2(),
  43. fn2(), fn2()
  44. ])
  45. })
  46. })