Sporalize-api / tests /single-flight.test.ts
Shoraky's picture
Improve backend request performance
82b44e7
Raw History Blame Contribute Delete
831 Bytes
import assert from "node:assert/strict";
import { test } from "node:test";
import { singleFlight } from "../src/single-flight.js";
test("shares concurrent validation, isolates tokens, and revalidates after completion", async () => {
let calls = 0;
const run = singleFlight(async (token: string) => { calls++; return token; });
const first = run("one");
assert.equal(first, run("one"));
assert.notEqual(first, run("two"));
assert.equal(await first, "one");
assert.equal(calls, 2);
await run("one");
assert.equal(calls, 3);
});
test("does not retain failed validation", async () => {
let calls = 0;
const run = singleFlight(async () => { if (++calls === 1) throw new Error("network"); return "verified"; });
await assert.rejects(run("token"), /network/);
assert.equal(await run("token"), "verified");
});