import { describe, it, expect, vi, beforeEach } from "vitest"; vi.mock("../lib/config.js", () => ({ getConfig: vi.fn(() => ({ apiUrl: "https://api.skills-hub.ai" })), saveConfig: vi.fn(), })); vi.mock("open", () => ({ default: vi.fn() })); vi.mock("node:http", () => ({ createServer: vi.fn(() => ({ listen: vi.fn(), close: vi.fn(), })), })); import { loginCommand } from "./login.js"; import { saveConfig } from "../lib/config.js"; const mockSaveConfig = vi.mocked(saveConfig); beforeEach(() => { vi.clearAllMocks(); // Reset Commander's stored option values to prevent state leaking between tests loginCommand.setOptionValue("apiKey", undefined); loginCommand.setOptionValue("provider", undefined); }); describe("login", () => { it("saves API key when --api-key provided", async () => { const log = vi.spyOn(console, "log").mockImplementation(() => {}); await loginCommand.parseAsync( ["node", "login", "--api-key", "sk_test_123"], { from: "node" }, ); expect(mockSaveConfig).toHaveBeenCalledWith({ apiKey: "sk_test_123" }); const output = log.mock.calls.map((c) => c[0]).join("\n"); expect(output).toContain("API key saved"); log.mockRestore(); }); it("starts browser OAuth flow when no --api-key", async () => { const { createServer } = await import("node:http"); const log = vi.spyOn(console, "log").mockImplementation(() => {}); // Mock listen is a no-op so the action completes after calling createServer + listen await loginCommand.parseAsync(["node", "login"], { from: "node" }); expect(vi.mocked(createServer)).toHaveBeenCalled(); const output = log.mock.calls.map((c) => c[0]).join("\n"); expect(output).toContain("Opening GitHub login"); log.mockRestore(); }); it("starts Google OAuth flow when --provider google", async () => { const { createServer } = await import("node:http"); const log = vi.spyOn(console, "log").mockImplementation(() => {}); await loginCommand.parseAsync(["node", "login", "--provider", "google"], { from: "node", }); expect(vi.mocked(createServer)).toHaveBeenCalled(); const output = log.mock.calls.map((c) => c[0]).join("\n"); expect(output).toContain("Opening Google login"); log.mockRestore(); }); });