Array.fromAsync.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. test("length is 1", () => {
  2. expect(Array.fromAsync).toHaveLength(1);
  3. });
  4. describe("normal behavior", () => {
  5. function checkResult(promise, type = Array) {
  6. expect(promise).toBeInstanceOf(Promise);
  7. let error = null;
  8. let passed = false;
  9. promise
  10. .then(value => {
  11. expect(value instanceof type).toBeTrue();
  12. expect(value[0]).toBe(0);
  13. expect(value[1]).toBe(2);
  14. expect(value[2]).toBe(4);
  15. passed = true;
  16. })
  17. .catch(value => {
  18. error = value;
  19. });
  20. runQueuedPromiseJobs();
  21. expect(error).toBeNull();
  22. expect(passed).toBeTrue();
  23. }
  24. test("async from sync iterable no mapfn", () => {
  25. const input = [0, Promise.resolve(2), Promise.resolve(4)].values();
  26. const promise = Array.fromAsync(input);
  27. checkResult(promise);
  28. });
  29. test("from object of promises no mapfn", () => {
  30. let promise = Array.fromAsync({
  31. length: 3,
  32. 0: Promise.resolve(0),
  33. 1: Promise.resolve(2),
  34. 2: Promise.resolve(4),
  35. });
  36. checkResult(promise);
  37. });
  38. test("async from sync iterable with mapfn", () => {
  39. const input = [Promise.resolve(0), 1, Promise.resolve(2)].values();
  40. const promise = Array.fromAsync(input, async element => element * 2);
  41. checkResult(promise);
  42. });
  43. test("from object of promises with mapfn", () => {
  44. let promise = Array.fromAsync(
  45. {
  46. length: 3,
  47. 0: Promise.resolve(0),
  48. 1: Promise.resolve(1),
  49. 2: Promise.resolve(2),
  50. },
  51. async element => element * 2
  52. );
  53. checkResult(promise);
  54. });
  55. test("does not double construct from array like object", () => {
  56. let callCount = 0;
  57. class TestArray {
  58. constructor() {
  59. callCount += 1;
  60. }
  61. }
  62. let promise = Array.fromAsync.call(TestArray, {
  63. length: 3,
  64. 0: Promise.resolve(0),
  65. 1: Promise.resolve(2),
  66. 2: Promise.resolve(4),
  67. });
  68. checkResult(promise, TestArray);
  69. expect(callCount).toBe(1);
  70. });
  71. });