Open History to see the last commit
1import { Atom, AtomRegistry } from "effect/reactivity";
2import { describe, expect, it } from "vite-plus/test";
3
4import { revisionedQuery } from "./revisionedQuery";
5
6// A stand-in query that counts its fetches.
7function setup() {
8 let fetches = 0;
9 // Node removal runs on the registry's scheduler; releasing flushes it so the
10 // next mount of the same revision builds a fresh node, as a React remount does.
11 const scheduled: Array<() => void> = [];
12 const registry = AtomRegistry.make({
13 scheduleTask: (task) => {
14 scheduled.push(task);
15 return () => {};
16 },
17 });
18 const query = Atom.make(() => {
19 fetches += 1;
20 return fetches;
21 }).pipe(Atom.keepAlive);
22 const mount = (revision: string | null | undefined) => {
23 const release = registry.mount(revisionedQuery(query, revision));
24 return () => {
25 release();
26 for (const task of scheduled.splice(0)) task();
27 };
28 };
29 return { registry, query, mount, fetches: () => fetches };
30}
31
32describe("revisionedQuery", () => {
33 it("refetches once per new revision, not on the first read or a remount", () => {
34 const { mount, fetches } = setup();
35
36 mount("mutation-1")();
37 expect(fetches()).toBe(1);
38
39 mount("mutation-1")();
40 expect(fetches()).toBe(1);
41
42 mount("mutation-2")();
43 expect(fetches()).toBe(2);
44 });
45
46 it("does not ping-pong while readers of the old and new revision overlap", () => {
47 const { mount, fetches } = setup();
48
49 const releaseOld = mount("mutation-1");
50 const releaseNew = mount("mutation-2");
51 expect(fetches()).toBe(2);
52 releaseOld();
53 releaseNew();
54 });
55
56 it("refetches when an earlier revision is read again", () => {
57 const { mount, fetches } = setup();
58
59 mount("mutation-1")();
60 mount("mutation-2")();
61 mount("mutation-1")();
62 expect(fetches()).toBe(3);
63 });
64
65 it("refetches a query another reader already cached on its first revisioned read", () => {
66 const { mount, fetches } = setup();
67
68 mount(undefined)();
69 expect(fetches()).toBe(1);
70
71 mount("mutation-1")();
72 expect(fetches()).toBe(2);
73
74 mount("mutation-1")();
75 expect(fetches()).toBe(2);
76 });
77
78 it("does not refetch a cached query on a first read before any workspace change", () => {
79 const { mount, fetches } = setup();
80
81 mount(undefined)();
82 mount(null)();
83 expect(fetches()).toBe(1);
84 });
85
86 it("leaves the query alone when read without a revision", () => {
87 const { mount, query, fetches } = setup();
88
89 mount("mutation-1")();
90 expect(revisionedQuery(query, undefined)).toBe(query);
91 mount(undefined)();
92 mount("mutation-1")();
93 expect(fetches()).toBe(1);
94 });
95
96 it("refetches the query when the reader is refreshed", () => {
97 const { registry, query, mount, fetches } = setup();
98
99 const release = mount("mutation-1");
100 registry.refresh(revisionedQuery(query, "mutation-1"));
101 expect(fetches()).toBe(2);
102 release();
103 });
104});