Skip to content
Source
Sign inSign up

coalescedRun.test.ts

57 lines1.5 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2​
3import { coalescedRun } from "./coalescedRun";
4​
5function deferredRuns() {
6 const runs: Array<PromiseWithResolvers<void>> = [];
7 const run = () => {
8 const next = Promise.withResolvers<void>();
9 runs.push(next);
10 return next.promise;
11 };
12 return { runs, run };
14​
15describe("coalescedRun", () => {
16 it("queues one more run for calls made while a run is in flight", async () => {
17 const { runs, run } = deferredRuns();
18 const refresh = coalescedRun(run);
19​
20 const first = refresh();
21 const second = refresh();
22 const third = refresh();
23 expect(third).toBe(second);
24 expect(runs).toHaveLength(1);
25​
26 runs[0]!.resolve();
27 await first;
28 await vi.waitFor(() => expect(runs).toHaveLength(2));
29​
30 runs[1]!.resolve();
31 await second;
32 expect(runs).toHaveLength(2);
33 });
34​
35 it("hands a queued run's failure to the call that asked for it", async () => {
36 const { runs, run } = deferredRuns();
37 const refresh = coalescedRun(run);
38​
39 const first = refresh();
40 const second = refresh();
41 runs[0]!.resolve();
42 await first;
43 await vi.waitFor(() => expect(runs).toHaveLength(2));
44 runs[1]!.reject(new Error("read failed"));
45 await expect(second).rejects.toThrow("read failed");
46 });
47​
48 it("runs once per call when calls do not overlap", async () => {
49 let count = 0;
50 const refresh = coalescedRun(async () => {
51 count += 1;
52 });
53 await refresh();
54 await refresh();
55 expect(count).toBe(2);
56 });
57});