/ opencodehub / cli / src / commands / config-command.test.ts
Swadhin Biswas feat(cli): expand command coverage and config support · 3/6/2026
7e372c1
72 lines · 2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { mkdtempSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";

type ConfigCommandModule = typeof import("./config/index.js");
type ConfigModule = typeof import("../lib/config.js");

let configCommandMod: ConfigCommandModule;
let configMod: ConfigModule;

beforeAll(async () => {
  const tmpDir = mkdtempSync(path.join(os.tmpdir(), "och-cli-config-cmd-test-"));
  process.env.XDG_CONFIG_HOME = tmpDir;
  process.env.XDG_DATA_HOME = tmpDir;
  process.env.OCH_DISABLE_KEYCHAIN = "1";

  configMod = await import("../lib/config.js");
  configCommandMod = await import("./config/index.js");
});

beforeEach(() => {
  configMod.clearConfig();
  vi.restoreAllMocks();
});

describe("config doctor command", () => {
  it("exits with code 1 when required config is missing", async () => {
    const exitSpy = vi
      .spyOn(process, "exit")
      .mockImplementation(((code?: number) => {
        throw new Error(`EXIT_${code ?? 0}`);
      }) as any);

    await expect(
      configCommandMod.configCommands.parseAsync(
        ["doctor"],
        { from: "user" },
      ),
    ).rejects.toThrow("EXIT_1");

    expect(exitSpy).toHaveBeenCalledWith(1);
  });

  it("succeeds when server and token are valid", async () => {
    configMod.saveConfig({
      serverUrl: "https://git.example.com",
      token: "token_12345678",
    });

    const fetchMock = vi.fn(async () =>
      new Response(JSON.stringify({ data: { username: "alice" } }), {
        status: 200,
        headers: { "content-type": "application/json" },
      }),
    );
    vi.stubGlobal("fetch", fetchMock);

    const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
      throw new Error("UNEXPECTED_EXIT");
    }) as any);

    await configCommandMod.configCommands.parseAsync(
      ["doctor"],
      { from: "user" },
    );

    expect(fetchMock).toHaveBeenCalled();
    expect(exitSpy).not.toHaveBeenCalled();
  });
});