Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

paced-per-record.test.ts

61 lines2.1 KB

1import type { Transaction } from "@tanstack/react-db";
2import { expect, it } from "vite-plus/test";
3​
4import { pacedPerRecord } from "./paced-per-record";
5​
6/** Stands in for a transaction: all the helper uses is `when("settled")`. */
7function fakeTransaction() {
8 let settle!: () => void;
9 const settled = new Promise<void>((resolve) => (settle = resolve));
10 const fake = {
11 state: "pending",
12 when: () => settled,
13 rollback: () => {
14 fake.state = "failed";
15 settle();
16 },
17 };
18 const transaction = fake as unknown as Transaction<object>;
19 return { transaction, settle: async () => (settle(), await settled, await tick()) };
21​
22const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
23​
24it("shares one instance per record until all its transactions settle", async () => {
25 const created: string[] = [];
26 const transactions = [fakeTransaction(), fakeTransaction(), fakeTransaction()];
27 let next = 0;
28 const records = pacedPerRecord((id) => {
29 created.push(id);
30 return () => transactions[next++]!.transaction;
31 });
32​
33 records.mutate("a", undefined);
34 records.mutate("a", undefined);
35 expect(created).toEqual(["a"]);
36​
37 await transactions[0]!.settle();
38 records.mutate("a", undefined); // "a" still has an unsettled transaction: same instance
39 expect(created).toEqual(["a"]);
40​
41 await transactions[1]!.settle();
42 await transactions[2]!.settle();
43 next = 0;
44 transactions.splice(0, 3, fakeTransaction(), fakeTransaction(), fakeTransaction());
45 records.mutate("a", undefined); // all settled: a fresh instance
46 expect(created).toEqual(["a", "a"]);
47});
48​
49it("cancels a record's changes that haven't started saving", async () => {
50 const pending = fakeTransaction();
51 const saving = fakeTransaction();
52 (saving.transaction as { state: string }).state = "persisting";
53 const queue = [saving, pending];
54 const records = pacedPerRecord(() => () => queue.shift()!.transaction);
55 records.mutate("a", undefined);
56 records.mutate("a", undefined);
57​
58 records.cancelPending("a");
59 expect(pending.transaction.state).toBe("failed");
60 expect(saving.transaction.state).toBe("persisting");
61});