sidebarTaskPreferences.test.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. SIDEBAR_TASK_PREFERENCES_STORAGE_KEY,
  4. persistSidebarTaskPreferences,
  5. readSidebarTaskPreferences,
  6. } from "@/lib/sidebarTaskPreferences.js";
  7. function createStorageMock(initial: Record<string, string> = {}) {
  8. const storage = new Map(Object.entries(initial));
  9. return {
  10. getItem(key: string) {
  11. return storage.get(key) ?? null;
  12. },
  13. setItem(key: string, value: string) {
  14. storage.set(key, value);
  15. },
  16. };
  17. }
  18. function installThrowingLocalStorageGetter() {
  19. const windowStub = {};
  20. Object.defineProperty(windowStub, "localStorage", {
  21. configurable: true,
  22. get() {
  23. throw new Error("SecurityError");
  24. },
  25. });
  26. vi.stubGlobal("window", windowStub);
  27. }
  28. afterEach(() => {
  29. vi.unstubAllGlobals();
  30. });
  31. describe("sidebarTaskPreferences", () => {
  32. it("默认使用 project 和 updated", () => {
  33. expect(readSidebarTaskPreferences(createStorageMock())).toEqual({
  34. organizeBy: "project",
  35. sortBy: "updated",
  36. });
  37. });
  38. it("持久化并恢复 timeline 和排序设置", () => {
  39. const storage = createStorageMock();
  40. persistSidebarTaskPreferences(
  41. { organizeBy: "chronological", sortBy: "created" },
  42. storage,
  43. );
  44. expect(readSidebarTaskPreferences(storage)).toEqual({
  45. organizeBy: "chronological",
  46. sortBy: "created",
  47. });
  48. });
  49. it("坏数据安全回退默认值", () => {
  50. const storage = createStorageMock({
  51. [SIDEBAR_TASK_PREFERENCES_STORAGE_KEY]: JSON.stringify({
  52. organizeBy: "bad",
  53. sortBy: "wat",
  54. }),
  55. });
  56. expect(readSidebarTaskPreferences(storage)).toEqual({
  57. organizeBy: "project",
  58. sortBy: "updated",
  59. });
  60. });
  61. it("localStorage getter 抛错时读取默认值且写入不抛错", () => {
  62. installThrowingLocalStorageGetter();
  63. expect(readSidebarTaskPreferences()).toEqual({
  64. organizeBy: "project",
  65. sortBy: "updated",
  66. });
  67. expect(() =>
  68. persistSidebarTaskPreferences({ organizeBy: "chronological", sortBy: "created" }),
  69. ).not.toThrow();
  70. });
  71. });