Skip to content

Commit 5d21567

Browse files
utils.ts too
1 parent 6bc82a2 commit 5d21567

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

.DS_Store

6 KB
Binary file not shown.

src/utils.test.ts

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
3+
import { execOrThrow } from "./utils.js";
4+
5+
const mockExec = vi.fn();
6+
7+
vi.mock("node:child_process", () => ({
8+
default: {
9+
get exec() {
10+
return mockExec;
11+
},
12+
},
13+
}));
14+
15+
describe("execOrThrow", () => {
16+
it("throws an error when exec prints to stderr", async () => {
17+
mockExec.mockImplementation((command, callback) => {
18+
callback(null, { stderr: "Oh no!" });
19+
});
20+
21+
await expect(
22+
async () => await execOrThrow("ls"),
23+
).rejects.toMatchInlineSnapshot(`[Error: Oh no!]`);
24+
});
25+
26+
it("returns stdout when exec doesn't print to stderr", async () => {
27+
const stdout = "abc123";
28+
29+
mockExec.mockImplementation((command, callback) => {
30+
callback(null, { stdout });
31+
});
32+
33+
const actual = await execOrThrow("ls");
34+
35+
expect(actual).toEqual(stdout);
36+
});
37+
});

src/utils.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import cp from "node:child_process";
22
import { promisify } from "node:util";
33

4-
const exec = promisify(cp.exec);
5-
64
export async function execOrThrow(command: string) {
5+
const exec = promisify(cp.exec);
76
const { stderr, stdout } = await exec(command);
87

98
if (stderr) {

0 commit comments

Comments
 (0)