commandCenterSearchHistory.test.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. clearCommandCenterSearchHistory,
  4. pushCommandCenterSearchHistory,
  5. readCommandCenterSearchHistory,
  6. } from "@/command-center/commandCenterSearchHistory.js";
  7. function createLocalStorageMock(): Storage {
  8. const values = new Map<string, string>();
  9. return {
  10. get length() {
  11. return values.size;
  12. },
  13. clear: vi.fn(() => values.clear()),
  14. getItem: vi.fn((key: string) => values.get(key) ?? null),
  15. key: vi.fn((index: number) => Array.from(values.keys())[index] ?? null),
  16. removeItem: vi.fn((key: string) => values.delete(key)),
  17. setItem: vi.fn((key: string, value: string) => values.set(key, value)),
  18. };
  19. }
  20. describe("commandCenterSearchHistory", () => {
  21. beforeEach(() => {
  22. vi.stubGlobal("window", {
  23. localStorage: createLocalStorageMock(),
  24. });
  25. });
  26. afterEach(() => {
  27. vi.unstubAllGlobals();
  28. });
  29. it("dedupes entries by query text across scopes", () => {
  30. pushCommandCenterSearchHistory({
  31. workspaceKey: "workspace-a",
  32. query: " auth ",
  33. scope: "files",
  34. });
  35. pushCommandCenterSearchHistory({
  36. workspaceKey: "workspace-a",
  37. query: "AUTH",
  38. scope: "files",
  39. });
  40. pushCommandCenterSearchHistory({
  41. workspaceKey: "workspace-a",
  42. query: "auth",
  43. scope: "commands",
  44. });
  45. expect(
  46. readCommandCenterSearchHistory("workspace-a").map((entry) => ({
  47. query: entry.query,
  48. scope: entry.scope,
  49. })),
  50. ).toEqual([{ query: "auth", scope: "commands" }]);
  51. });
  52. it("keeps at most 20 entries per workspace key", () => {
  53. for (let index = 0; index < 25; index += 1) {
  54. pushCommandCenterSearchHistory({
  55. workspaceKey: "workspace-a",
  56. query: `query-${index}`,
  57. scope: "all",
  58. });
  59. }
  60. const entries = readCommandCenterSearchHistory("workspace-a");
  61. expect(entries).toHaveLength(20);
  62. expect(entries[0]?.query).toBe("query-24");
  63. expect(entries.at(-1)?.query).toBe("query-5");
  64. });
  65. it("isolates and clears history by workspace key", () => {
  66. pushCommandCenterSearchHistory({
  67. workspaceKey: "workspace-a",
  68. query: "open settings",
  69. scope: "commands",
  70. });
  71. pushCommandCenterSearchHistory({
  72. workspaceKey: "workspace-b",
  73. query: "readme",
  74. scope: "files",
  75. });
  76. clearCommandCenterSearchHistory("workspace-a");
  77. expect(readCommandCenterSearchHistory("workspace-a")).toEqual([]);
  78. expect(readCommandCenterSearchHistory("workspace-b").map((entry) => entry.query)).toEqual([
  79. "readme",
  80. ]);
  81. });
  82. });