exec.test.ts (2517B)
1 import { describe, it, expect, beforeEach, vi } from "vitest"; 2 import { execFile } from "node:child_process"; 3 4 import { exec } from "./exec"; 5 6 vi.mock("node:child_process", async (importOriginal) => { 7 const actual = await importOriginal<typeof import("node:child_process")>(); 8 return { 9 ...actual, 10 execFile: vi.fn(), 11 }; 12 }); 13 14 describe("exec", () => { 15 const execFileMock = execFile as unknown as ReturnType<typeof vi.fn>; 16 17 beforeEach(() => { 18 vi.clearAllMocks(); 19 }); 20 21 it("resolves stdout, stderr, and status for a successful command", async () => { 22 execFileMock.mockImplementation( 23 ( 24 _command: string, 25 _args: readonly string[], 26 _options: unknown, 27 callback: (error: unknown, stdout: string, stderr: string) => void, 28 ) => callback(null, "hello\n", ""), 29 ); 30 31 const result = await exec("git", ["status"]); 32 33 expect(result).toEqual({ 34 status: 0, 35 stdout: "hello\n", 36 stderr: "", 37 }); 38 expect(execFileMock).toHaveBeenCalledWith( 39 "git", 40 ["status"], 41 expect.objectContaining({ maxBuffer: 10 * 1024 * 1024 }), 42 expect.any(Function), 43 ); 44 }); 45 46 it("resolves a numeric exit status instead of rejecting", async () => { 47 execFileMock.mockImplementation( 48 ( 49 _command: string, 50 _args: readonly string[], 51 _options: unknown, 52 callback: ( 53 error: { code: number }, 54 stdout: string, 55 stderr: string, 56 ) => void, 57 ) => callback({ code: 2 }, "", "failed"), 58 ); 59 60 const result = await exec("limactl", ["list", "missing"]); 61 62 expect(result).toEqual({ 63 status: 2, 64 stdout: "", 65 stderr: "failed", 66 }); 67 }); 68 69 it("uses status 1 for non-numeric execution errors", async () => { 70 execFileMock.mockImplementation( 71 ( 72 _command: string, 73 _args: readonly string[], 74 _options: unknown, 75 callback: ( 76 error: { code: string }, 77 stdout: string, 78 stderr: string, 79 ) => void, 80 ) => callback({ code: "ENOENT" }, "", ""), 81 ); 82 83 const result = await exec("missing-command", []); 84 85 expect(result.status).toBe(1); 86 }); 87 88 it("resolves status 1 when execFile throws synchronously", async () => { 89 execFileMock.mockImplementation(() => { 90 throw new Error("synchronous failure"); 91 }); 92 93 const result = await exec("broken", []); 94 95 expect(result).toEqual({ 96 status: 1, 97 stdout: "", 98 stderr: "", 99 }); 100 }); 101 });