|
1 | | -import { describe, expect, it } from "vite-plus/test"; |
| 1 | +import { describe, expect, it, vi } from "vite-plus/test"; |
2 | 2 |
|
3 | 3 | import { coalescedRun } from "./coalescedRun"; |
4 | 4 |
|
| 5 | +function 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 }; |
| 13 | +} |
| 14 | + |
5 | 15 | describe("coalescedRun", () => { |
6 | | - it("runs once more when called while a run is in flight", async () => { |
7 | | - const runs: Array<PromiseWithResolvers<void>> = []; |
8 | | - const refresh = coalescedRun(() => { |
9 | | - const run = Promise.withResolvers<void>(); |
10 | | - runs.push(run); |
11 | | - return run.promise; |
12 | | - }); |
| 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); |
13 | 19 |
|
14 | 20 | const first = refresh(); |
15 | | - const joined = refresh(); |
16 | | - refresh(); |
17 | | - expect(joined).toBe(first); |
| 21 | + const second = refresh(); |
| 22 | + const third = refresh(); |
| 23 | + expect(third).toBe(second); |
18 | 24 | expect(runs).toHaveLength(1); |
19 | 25 |
|
20 | 26 | runs[0]!.resolve(); |
21 | 27 | await first; |
22 | | - await Promise.resolve(); |
23 | | - expect(runs).toHaveLength(2); |
| 28 | + await vi.waitFor(() => expect(runs).toHaveLength(2)); |
24 | 29 |
|
25 | 30 | runs[1]!.resolve(); |
26 | | - await runs[1]!.promise; |
27 | | - await Promise.resolve(); |
| 31 | + await second; |
28 | 32 | expect(runs).toHaveLength(2); |
29 | 33 | }); |
30 | 34 |
|
31 | | - it("does not run again when nothing was asked during the run", async () => { |
| 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 () => { |
32 | 49 | let count = 0; |
33 | 50 | const refresh = coalescedRun(async () => { |
34 | 51 | count += 1; |
35 | 52 | }); |
36 | 53 | await refresh(); |
37 | | - await Promise.resolve(); |
38 | | - expect(count).toBe(1); |
| 54 | + await refresh(); |
| 55 | + expect(count).toBe(2); |
39 | 56 | }); |
40 | 57 | }); |
0 commit comments