This repository has no description
1import { describe, expect, it } from "vitest";
2import { createAction } from "./action.svelte";
3
4describe("createAction", () => {
5 it("derives ergonomic projections from one state", async () => {
6 let resolve!: (value: string) => void;
7 const action = createAction(() => new Promise<string>((done) => (resolve = done)));
8
9 expect(action.loading).toBe(false);
10 expect(action.data).toBeUndefined();
11 expect(action.error).toBeUndefined();
12
13 const running = action.run();
14 expect(action.loading).toBe(true);
15
16 resolve("done");
17 await running;
18 expect(action.data).toBe("done");
19 });
20
21 it("converts failures", async () => {
22 const action = createAction(
23 async () => {
24 throw new Error("nope");
25 },
26 (cause) => (cause instanceof Error ? cause.message : "unknown")
27 );
28
29 await action.run();
30 expect(action.error).toBe("nope");
31 });
32
33 it("ignores an older result after a newer run starts", async () => {
34 const resolvers: Array<(value: string) => void> = [];
35 const names: string[] = [];
36 const action = createAction(
37 (name: string) =>
38 new Promise<string>((resolve) => {
39 names.push(name);
40 resolvers.push(resolve);
41 })
42 );
43 const first = action.run("first");
44 const second = action.run("second");
45 expect(names).toEqual(["first", "second"]);
46 expect(action.args).toEqual(["second"]);
47
48 resolvers[0]("stale");
49 await first;
50 expect(action.loading).toBe(true);
51
52 resolvers[1]("current");
53 await second;
54 expect(action.data).toBe("current");
55 expect(action.args).toBeUndefined();
56 });
57});