aboutsummaryrefslogtreecommitdiff
path: root/tests/storage.test.ts
blob: 7d6ba73f7db463f71c1a38079f9190ef5259bdc0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*** IMPORT ------------------------------------------- ***/

import { assertEquals } from "jsr:@std/assert@^1.0.0";

/*** UTILITY ------------------------------------------ ***/

import {
  createLocalStorage,
  createMemoryStorage
} from "../source/library/state/storage.ts";

/*** TESTS -------------------------------------------- ***/

Deno.test("memory storage round-trips objects", () => {
  const storage = createMemoryStorage();
  storage.set("k", { hello: "world" });
  assertEquals(storage.get<{ hello: string }>("k"), { hello: "world" });
});

Deno.test("memory storage returns null for missing keys", () => {
  const storage = createMemoryStorage();
  assertEquals(storage.get("missing"), null);
});

Deno.test("memory storage remove clears a key", () => {
  const storage = createMemoryStorage();
  storage.set("k", 42);
  storage.remove("k");
  assertEquals(storage.get("k"), null);
});

Deno.test("memory storage instances are isolated", () => {
  const a = createMemoryStorage();
  const b = createMemoryStorage();
  a.set("shared", 1);
  assertEquals(b.get("shared"), null);
});

Deno.test("local storage namespaces keys", () => {
  globalThis.localStorage.clear();

  const alpha = createLocalStorage("alpha");
  const beta = createLocalStorage("beta");

  alpha.set("shared", { tag: "a" });
  beta.set("shared", { tag: "b" });

  assertEquals(alpha.get<{ tag: string }>("shared"), { tag: "a" });
  assertEquals(beta.get<{ tag: string }>("shared"), { tag: "b" });
  assertEquals(globalThis.localStorage.getItem("alpha:shared"), JSON.stringify({ tag: "a" }));
  assertEquals(globalThis.localStorage.getItem("beta:shared"), JSON.stringify({ tag: "b" }));

  globalThis.localStorage.clear();
});

Deno.test("local storage remove respects the namespace", () => {
  globalThis.localStorage.clear();

  const alpha = createLocalStorage("alpha");
  const beta = createLocalStorage("beta");

  alpha.set("k", 1);
  beta.set("k", 2);

  alpha.remove("k");
  assertEquals(alpha.get("k"), null);
  assertEquals(beta.get<number>("k"), 2);

  globalThis.localStorage.clear();
});

Deno.test("local storage returns null on malformed JSON", () => {
  globalThis.localStorage.clear();
  globalThis.localStorage.setItem("alpha:bad", "not-json");

  const alpha = createLocalStorage("alpha");
  assertEquals(alpha.get("bad"), null);

  globalThis.localStorage.clear();
});