2023-09-01 18:00:51 +02:00
|
|
|
import { ExecutorQueue } from '$lib/utils/executor-queue';
|
|
|
|
|
|
|
|
describe('Executor Queue test', function () {
|
|
|
|
it('should run all promises', async function () {
|
|
|
|
const eq = new ExecutorQueue({ concurrency: 1 });
|
|
|
|
const n1 = await eq.addTask(() => Promise.resolve(10));
|
|
|
|
expect(n1).toBe(10);
|
|
|
|
const n2 = await eq.addTask(() => Promise.resolve(11));
|
|
|
|
expect(n2).toBe(11);
|
|
|
|
const n3 = await eq.addTask(() => Promise.resolve(12));
|
|
|
|
expect(n3).toBe(12);
|
|
|
|
});
|
|
|
|
|
|
|
|
it('should respect concurrency parameter', function () {
|
2024-01-01 18:36:49 +01:00
|
|
|
vi.useFakeTimers();
|
2023-09-01 18:00:51 +02:00
|
|
|
const eq = new ExecutorQueue({ concurrency: 3 });
|
|
|
|
|
2024-01-01 18:36:49 +01:00
|
|
|
const finished = vi.fn();
|
|
|
|
const started = vi.fn();
|
2023-09-01 18:00:51 +02:00
|
|
|
|
|
|
|
const timeoutPromiseBuilder = (delay: number, id: string) =>
|
|
|
|
new Promise((resolve) => {
|
|
|
|
started();
|
|
|
|
setTimeout(() => {
|
|
|
|
finished();
|
2024-01-01 18:36:49 +01:00
|
|
|
resolve(id);
|
2023-09-01 18:00:51 +02:00
|
|
|
}, delay);
|
|
|
|
});
|
|
|
|
|
|
|
|
// The first 3 should be finished within 200ms (concurrency 3)
|
2024-02-27 17:37:37 +01:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
2023-09-01 18:00:51 +02:00
|
|
|
eq.addTask(() => timeoutPromiseBuilder(100, 'T1'));
|
2024-02-27 17:37:37 +01:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
2023-09-01 18:00:51 +02:00
|
|
|
eq.addTask(() => timeoutPromiseBuilder(200, 'T2'));
|
2024-02-27 17:37:37 +01:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
2023-09-01 18:00:51 +02:00
|
|
|
eq.addTask(() => timeoutPromiseBuilder(150, 'T3'));
|
|
|
|
// The last task will be executed after 200ms and will finish at 400ms
|
2024-02-27 17:37:37 +01:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
2023-09-01 18:00:51 +02:00
|
|
|
eq.addTask(() => timeoutPromiseBuilder(200, 'T4'));
|
|
|
|
|
|
|
|
expect(finished).not.toBeCalled();
|
|
|
|
expect(started).toHaveBeenCalledTimes(3);
|
|
|
|
|
2024-01-01 18:36:49 +01:00
|
|
|
vi.advanceTimersByTime(100);
|
2023-09-01 18:00:51 +02:00
|
|
|
expect(finished).toHaveBeenCalledTimes(1);
|
|
|
|
|
2024-01-01 18:36:49 +01:00
|
|
|
vi.advanceTimersByTime(250);
|
2023-09-01 18:00:51 +02:00
|
|
|
expect(finished).toHaveBeenCalledTimes(3);
|
|
|
|
// expect(started).toHaveBeenCalledTimes(4)
|
|
|
|
|
|
|
|
//TODO : fix The test ...
|
|
|
|
|
2024-01-01 18:36:49 +01:00
|
|
|
vi.runAllTimers();
|
|
|
|
vi.useRealTimers();
|
2023-09-01 18:00:51 +02:00
|
|
|
});
|
|
|
|
});
|