Eric Bower
·
04 Mar 24
persist.test.ts
1import { asserts, describe, it } from "../test.ts";
2import {
3 createPersistor,
4 createSchema,
5 createStore,
6 PERSIST_LOADER_ID,
7 PersistAdapter,
8 persistStoreMdw,
9 slice,
10} from "../store/mod.ts";
11import { Ok, Operation, parallel, put, take } from "../mod.ts";
12
13const tests = describe("store");
14
15it(tests, "can persist to storage adapters", async () => {
16 const [schema, initialState] = createSchema({
17 token: slice.str(),
18 loaders: slice.loaders(),
19 cache: slice.table({ empty: {} }),
20 });
21 type State = typeof initialState;
22 let ls = "{}";
23 const adapter: PersistAdapter<State> = {
24 getItem: function* (_: string) {
25 return Ok(JSON.parse(ls));
26 },
27 setItem: function* (_: string, s: Partial<State>) {
28 ls = JSON.stringify(s);
29 return Ok(undefined);
30 },
31 removeItem: function* (_: string) {
32 return Ok(undefined);
33 },
34 };
35 const persistor = createPersistor<State>({ adapter, allowlist: ["token"] });
36 const mdw = persistStoreMdw(persistor);
37 const store = createStore({
38 initialState,
39 middleware: [mdw],
40 });
41
42 await store.run(function* (): Operation<void> {
43 yield* persistor.rehydrate();
44
45 const group = yield* parallel([
46 function* (): Operation<void> {
47 const action = yield* take<string>("SET_TOKEN");
48 yield* schema.update(schema.token.set(action.payload));
49 },
50 function* () {
51 yield* put({ type: "SET_TOKEN", payload: "1234" });
52 },
53 ]);
54 yield* group;
55 });
56
57 asserts.assertEquals(
58 ls,
59 '{"token":"1234"}',
60 );
61});
62
63it(tests, "rehydrates state", async () => {
64 const [schema, initialState] = createSchema({
65 token: slice.str(),
66 loaders: slice.loaders(),
67 cache: slice.table({ empty: {} }),
68 });
69 type State = typeof initialState;
70 let ls = JSON.stringify({ token: "123" });
71 const adapter: PersistAdapter<State> = {
72 getItem: function* (_: string) {
73 return Ok(JSON.parse(ls));
74 },
75 setItem: function* (_: string, s: Partial<State>) {
76 ls = JSON.stringify(s);
77 return Ok(undefined);
78 },
79 removeItem: function* (_: string) {
80 return Ok(undefined);
81 },
82 };
83 const persistor = createPersistor<State>({ adapter, allowlist: ["token"] });
84 const mdw = persistStoreMdw(persistor);
85 const store = createStore({
86 initialState,
87 middleware: [mdw],
88 });
89
90 await store.run(function* (): Operation<void> {
91 yield* persistor.rehydrate();
92 yield* schema.update(schema.loaders.success({ id: PERSIST_LOADER_ID }));
93 });
94
95 asserts.assertEquals(
96 store.getState().token,
97 "123",
98 );
99});