Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { readUsagePagePreferences, saveUsagePagePreferences } from "./usagePagePreferences";
4
5const key = "t3code:usage-page-preferences:v1";
6let values: Map<string, string>;
7let storage: Pick<Storage, "getItem" | "setItem">;
8
9beforeEach(() => {
10 values = new Map();
11 storage = {
12 getItem: (key) => values.get(key) ?? null,
13 setItem: (key, value) => {
14 values.set(key, value);
15 },
16 };
17 vi.stubGlobal("window", { localStorage: storage });
18 vi.spyOn(console, "error").mockImplementation(() => {});
19});
20
21afterEach(() => {
22 vi.restoreAllMocks();
23 vi.unstubAllGlobals();
24});
25
26describe("Usage page preferences", () => {
27 it("uses defaults when no preference has been saved", () => {
28 expect(readUsagePagePreferences()).toEqual({ metric: "limits", windowDays: 30 });
29 });
30
31 it.each([1, 7, 30, 90] as const)("round-trips every metric with a %i-day range", (windowDays) => {
32 for (const metric of ["cost", "tokens", "limits"] as const) {
33 saveUsagePagePreferences({ metric, windowDays });
34 expect(readUsagePagePreferences()).toEqual({ metric, windowDays });
35 }
36 });
37
38 it.each([
39 "not-json",
40 '{"metric":"unknown","windowDays":7}',
41 '{"metric":"cost","windowDays":365}',
42 ])("replaces invalid preferences on the next save: %s", (value) => {
43 values.set(key, value);
44 expect(readUsagePagePreferences()).toEqual({ metric: "limits", windowDays: 30 });
45 saveUsagePagePreferences({ metric: "tokens", windowDays: 7 });
46 expect(readUsagePagePreferences()).toEqual({ metric: "tokens", windowDays: 7 });
47 });
48
49 it("contains write failures and can save again after storage recovers", () => {
50 saveUsagePagePreferences({ metric: "cost", windowDays: 30 });
51 const write = vi.spyOn(storage, "setItem").mockImplementation(() => {
52 throw new Error("QuotaExceededError");
53 });
54 expect(() => saveUsagePagePreferences({ metric: "tokens", windowDays: 7 })).not.toThrow();
55 expect(readUsagePagePreferences()).toEqual({ metric: "cost", windowDays: 30 });
56 write.mockRestore();
57 saveUsagePagePreferences({ metric: "limits", windowDays: 7 });
58 expect(readUsagePagePreferences()).toEqual({ metric: "limits", windowDays: 7 });
59 });
60
61 it("contains failures when the browser blocks storage access", () => {
62 vi.stubGlobal("window", {
63 get localStorage() {
64 throw new Error("SecurityError");
65 },
66 });
67 expect(readUsagePagePreferences()).toEqual({ metric: "limits", windowDays: 30 });
68 expect(() => saveUsagePagePreferences({ metric: "tokens", windowDays: 7 })).not.toThrow();
69 });
70});