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([batch1, batch2, batch3]);
  18. });
  19. describe('error handling', () => {
  20. const all = [1, 2, 3, 4, 5, 6, 7, 8, '9', 10];
  21. const multiplyBy10 = async (num) => {
  22. if (typeof num !== 'number') {
  23. throw new Error('Is not number');
  24. }
  25. return num * 10;
  26. };
  27. describe('when throwIfRejected is true', () => {
  28. it('throws error when there is a Promise rejection', async () => {
  29. await expect(
  30. batchProcessPromiseAll(all, 5, multiplyBy10),
  31. ).rejects.toThrow('Is not number');
  32. });
  33. });
  34. describe('when throwIfRejected is false', () => {
  35. it("doesn't throw error when there is a Promise rejection", async () => {
  36. const expected = [10, 20, 30, 40, 50, 60, 70, 80, 100];
  37. await expect(
  38. batchProcessPromiseAll(all, 5, multiplyBy10, false),
  39. ).resolves.toStrictEqual(expected);
  40. });
  41. });
  42. });
  43. });