Repository navigation
Expand file tree
/
Copy pathclientPersistenceStorage.test.ts
More file actions
81 lines (74 loc) · 2.58 KB
/
Copy pathclientPersistenceStorage.test.ts
File metadata and controls
81 lines (74 loc) · 2.58 KB
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
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}
function getTestWindow(): Window & typeof globalThis {
const localStorage = createLocalStorageStub();
const testWindow = {
localStorage,
} as Window & typeof globalThis;
vi.stubGlobal("window", testWindow);
vi.stubGlobal("localStorage", localStorage);
return testWindow;
}
afterEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("clientPersistenceStorage", () => {
it.each(["not-json", '{"wordWrap":"invalid"}'])(
"does not treat invalid saved settings as absent: %s",
async (value) => {
const testWindow = getTestWindow();
testWindow.localStorage.setItem("t3code:client-settings:v1", value);
const { readBrowserClientSettings } = await import("./clientPersistenceStorage");
expect(() => readBrowserClientSettings()).toThrow(
expect.objectContaining({
_tag: "LocalStorageOperationError",
operation: "decode",
storageKey: "t3code:client-settings:v1",
}),
);
expect(testWindow.localStorage.getItem("t3code:client-settings:v1")).toBe(value);
},
);
it("preserves saved settings across a transient read failure", async () => {
const testWindow = getTestWindow();
const settings = { ...DEFAULT_CLIENT_SETTINGS, timestampFormat: "12-hour" as const };
testWindow.localStorage.setItem("t3code:client-settings:v1", JSON.stringify(settings));
const write = vi.spyOn(testWindow.localStorage, "setItem");
const failure = new Error("storage unavailable");
vi.spyOn(testWindow.localStorage, "getItem").mockImplementationOnce(() => {
throw failure;
});
const { readBrowserClientSettings } = await import("./clientPersistenceStorage");
expect(() => readBrowserClientSettings()).toThrow(
expect.objectContaining({
_tag: "LocalStorageOperationError",
operation: "read",
storageKey: "t3code:client-settings:v1",
cause: failure,
}),
);
expect(readBrowserClientSettings()).toEqual(settings);
expect(write).not.toHaveBeenCalled();
});
});