promise.spec.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { batchProcessPromiseAll } from './promise';
  2. describe('batchProcessPromiseAll', () => {
  3. it('processes items in batch', async() => {
  4. const batch1 = [1, 2, 3, 4, 5];
  5. const batch2 = [6, 7, 8, 9, 10];
  6. const batch3 = [11, 12];
  7. const all = [...batch1, ...batch2, ...batch3];
  8. const actualProcessedBatches: number[][] = [];
  9. const result = await batchProcessPromiseAll(all, 5, async(num, i, arr) => {
  10. if (arr != null && i === 0) {
  11. actualProcessedBatches.push(arr);
  12. }
  13. return num * 10;
  14. });
  15. const expected = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120];
  16. expect(result).toStrictEqual(expected);
  17. expect(actualProcessedBatches).toStrictEqual([
  18. batch1,
  19. batch2,
  20. batch3,
  21. ]);
  22. });
  23. describe('error handling', () => {
  24. const all = [1, 2, 3, 4, 5, 6, 7, 8, '9', 10];
  25. const multiplyBy10 = async(num) => {
  26. if (typeof num !== 'number') {
  27. throw new Error('Is not number');
  28. }
  29. return num * 10;
  30. };
  31. describe('when throwIfRejected is true', () => {
  32. it('throws error when there is a Promise rejection', async() => {
  33. await expect(batchProcessPromiseAll(all, 5, multiplyBy10)).rejects.toThrow('Is not number');
  34. });
  35. });
  36. describe('when throwIfRejected is false', () => {
  37. it('doesn\'t throw error when there is a Promise rejection', async() => {
  38. const expected = [10, 20, 30, 40, 50, 60, 70, 80, 100];
  39. await expect(batchProcessPromiseAll(all, 5, multiplyBy10, false)).resolves.toStrictEqual(expected);
  40. });
  41. });
  42. });
  43. });