From 11c77441403614ea94a02542b9c994cdbaef78a0 Mon Sep 17 00:00:00 2001 From: edithatogo <15080672+edithatogo@users.noreply.github.com> Date: Fri, 21 Aug 2026 09:22:53 +0000 Subject: [PATCH] test(auth): add error handling tests for loadSession This commit addresses the testing gap in `loadSession` by adding unit tests that verify: - It returns null when the session file is missing (ENOENT) - It correctly propagates/throws non-ENOENT errors (like EACCES permission denied errors) - It correctly returns a parsed stored session on the happy path. The tests mock `fs/promises` to simulate these filesystem scenarios. --- src/auth/session-store.test.ts | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/auth/session-store.test.ts diff --git a/src/auth/session-store.test.ts b/src/auth/session-store.test.ts new file mode 100644 index 0000000..7bb2330 --- /dev/null +++ b/src/auth/session-store.test.ts @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import { describe, it, vi } from "vitest"; +import { loadSession } from "./session-store.js"; + +vi.mock("node:fs/promises", async (importOriginal) => { + const mod = await importOriginal(); + return { + ...mod, + readFile: vi.fn(mod.readFile), + }; +}); + +import { readFile } from "node:fs/promises"; +import { sessionFilePath } from "../config/paths.js"; + +describe("loadSession", () => { + it("returns null when the session file is missing (ENOENT)", async () => { + vi.mocked(readFile).mockRejectedValueOnce( + Object.assign(new Error("File not found"), { code: "ENOENT" }), + ); + + const session = await loadSession(); + assert.equal(session, null); + }); + + it("throws non-ENOENT errors when reading the session file fails", async () => { + vi.mocked(readFile).mockRejectedValueOnce( + Object.assign(new Error("Permission denied"), { code: "EACCES" }), + ); + + await assert.rejects(loadSession(), /Permission denied/); + }); + + it("returns the parsed session when the file exists and is valid", async () => { + const fakeSession = { + browserbaseSessionId: "fake-id", + publicationUrl: "https://example.substack.com", + createdAt: "2023-01-01T00:00:00.000Z", + updatedAt: "2023-01-01T00:00:00.000Z", + }; + vi.mocked(readFile).mockResolvedValueOnce(JSON.stringify(fakeSession)); + + const session = await loadSession(); + assert.deepEqual(session, fakeSession); + }); +});