typed-utilities
Version:
Strongly typed general purpose utilities
102 lines (91 loc) • 3.18 kB
JavaScript
;
var _ = require("..");
describe(`MapAsync`, () => {
test(`mapAsyncSerial`, async () => {
const log = [];
const fn = async value => {
await (0, _.sleep)(value);
log.push(value);
return value;
};
expect(await (0, _.mapAsyncSerial)([300, 100, 200], fn)).toEqual([300, 100, 200]);
expect(log).toEqual([300, 100, 200]);
});
test(`mapAsyncConcurrent without rejections`, async () => {
const log = [];
const fn = async value => {
await (0, _.sleep)(value);
log.push(value);
return value;
};
expect(await (0, _.mapAsyncConcurrent)([300, 100, 200], fn)).toEqual([300, 100, 200]);
expect(log).toEqual([100, 200, 300]);
});
test(`mapAsyncConcurrent with rejections`, async () => {
let countTrue = 0;
const fn = async ([b, delayMs]) => {
await (0, _.sleep)(delayMs);
if (b) {
countTrue++;
} else {
throw new Error();
}
};
const t = [[true, 10], [true, 30], [false, 20], [true, 50], [false, 100]];
await expect(() => Promise.all(t.map(fn))).rejects.toBeTruthy();
expect(countTrue).toEqual(1);
await (0, _.sleep)(200);
expect(countTrue).toEqual(3);
countTrue = 0;
await expect(() => (0, _.mapAsyncConcurrent)(t, fn)).rejects.toBeTruthy();
expect(countTrue).toEqual(3);
await expect(() => (0, _.mapAsyncConcurrent)(t, fn)).rejects.toBeInstanceOf(AggregateError);
expect(countTrue).toEqual(6);
});
test(`mapAsyncEntriesConcurrent`, async () => {
await expect((0, _.mapEntriesAsyncConcurrent)({})).resolves.toEqual({});
await expect((0, _.mapEntriesAsyncConcurrent)({
a: 1
})).resolves.toEqual({
a: 1
});
await expect((0, _.mapEntriesAsyncConcurrent)({
a: Promise.resolve(42)
})).resolves.toEqual({
a: 42
});
const input = {
a: Promise.resolve(42),
b: null,
c: Promise.resolve(null)
};
const output = await (0, _.mapEntriesAsyncConcurrent)(input);
expect(output.a).toEqual(42);
});
test(`resolveAllSerial, resolveAllConcurrent with identity (Promise.all-like)`, async () => {
const items = [Promise.resolve(1), Promise.resolve(null), Promise.resolve(3)];
expect(await (0, _.resolveAllSerial)(items)).toEqual([1, null, 3]);
expect(await (0, _.resolveAllConcurrent)(items)).toEqual([1, null, 3]);
const dynamicItems = [Promise.resolve(null), Promise.resolve(null), Promise.resolve(1), Promise.resolve(null), Promise.resolve(`hello`)];
expect(await (0, _.resolveAllConcurrent)(dynamicItems)).toEqual([null, null, 1, null, `hello`]);
});
test(`mapAsyncConcurrent with maxConcurrency`, async () => {
const items = [1, 2, 3, 4, 5];
let max = 0;
let current = 0;
const fn = async n => {
current++;
max = Math.max(max, current);
await (0, _.sleep)(1);
current--;
return 2 * n;
};
const result = await (0, _.mapAsyncConcurrent)(items, fn, {
maxConcurrency: 3
});
expect(result).toEqual([2, 4, 6, 8, 10]);
expect(max).toEqual(3);
expect(current).toEqual(0);
});
});
//# sourceMappingURL=iterAsync.test.js.map