attq/test/task-queue.test.ts

43 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

2026-02-06 07:59:19 +00:00
import { AsyncTaskQueue } from "../src/index";
test("example evaluates correctly", async () => {
jest.useFakeTimers();
const THROTTLE_DELAY_MS = 100;
const q = new AsyncTaskQueue<number>(
async () => {/* no-op */ },
)
// Handler will receive up to 4 items per batch.
.batchSize(4)
// Handler will be called at most once per 100 milliseconds.
.throttleMs(THROTTLE_DELAY_MS);
// Add items to the queue.
for (let n = 0; n < 1000; n++) {
q.push(n);
}
// Advance the clock incrementally and asynchronously so that we yield to the
// task queue control loop frequently. This should allow it to complete its
// work more or less as it would with real timers.
//
// Advance timers by a shorter duration than THROTTLE_DELAY_MS to test that
// the task queue throttles correctly according to wall time and not merely
// according to event loop ticks.
const fakeTimerIncrementMs = Math.ceil(THROTTLE_DELAY_MS / 2);
for (
let mockDelayMs = 0;
mockDelayMs < 4000;
mockDelayMs += fakeTimerIncrementMs
) {
await jest.advanceTimersByTimeAsync(fakeTimerIncrementMs);
}
expect(q.size()).toBeLessThan(850);
expect(q.size()).toBeGreaterThan(825);
q.drain();
expect(q.size()).toEqual(0);
});