recent.test.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { RECENT_CAP, addRecent, loadRecent, saveRecent } from "../src/recent.js";
  6. import type { EditorRecentEntry } from "../src/ipc.js";
  7. function entry(root: string, name = "p"): EditorRecentEntry {
  8. return { root, name };
  9. }
  10. describe("addRecent", () => {
  11. it("prepends new entries and dedupes by root", () => {
  12. const base = [entry("/a"), entry("/b")];
  13. const next = addRecent(base, entry("/b", "b2"));
  14. expect(next.map((e) => e.root)).toEqual(["/b", "/a"]);
  15. expect(next[0]?.name).toBe("b2");
  16. });
  17. it("caps the list at RECENT_CAP", () => {
  18. let list: EditorRecentEntry[] = [];
  19. for (let i = 0; i < RECENT_CAP + 3; i++) list = addRecent(list, entry(`/p${i}`));
  20. expect(list.length).toBe(RECENT_CAP);
  21. expect(list[0]?.root).toBe(`/p${RECENT_CAP + 2}`);
  22. });
  23. });
  24. describe("recent persistence", () => {
  25. it("roundtrips through a json file", async () => {
  26. const dir = await mkdtemp(join(tmpdir(), "editor-recent-"));
  27. try {
  28. const file = join(dir, "recent.json");
  29. const entries = [entry("/a", "A"), entry("/b", "B")];
  30. await saveRecent(file, entries);
  31. expect(await loadRecent(file)).toEqual(entries);
  32. } finally {
  33. await rm(dir, { recursive: true, force: true });
  34. }
  35. });
  36. it("returns [] for a missing file", async () => {
  37. const dir = await mkdtemp(join(tmpdir(), "editor-recent-"));
  38. try {
  39. expect(await loadRecent(join(dir, "nope.json"))).toEqual([]);
  40. } finally {
  41. await rm(dir, { recursive: true, force: true });
  42. }
  43. });
  44. it("returns [] for corrupt json and drops invalid entries", async () => {
  45. const dir = await mkdtemp(join(tmpdir(), "editor-recent-"));
  46. try {
  47. const corrupt = join(dir, "corrupt.json");
  48. const { writeFile } = await import("node:fs/promises");
  49. await writeFile(corrupt, "{ not json", "utf8");
  50. expect(await loadRecent(corrupt)).toEqual([]);
  51. const mixed = join(dir, "mixed.json");
  52. await writeFile(mixed, JSON.stringify([{ root: "/ok", name: "Ok" }, { root: 42 }, "junk"]), "utf8");
  53. expect(await loadRecent(mixed)).toEqual([{ root: "/ok", name: "Ok" }]);
  54. } finally {
  55. await rm(dir, { recursive: true, force: true });
  56. }
  57. });
  58. });