Skip to content

Instantly share code, notes, and snippets.

@manekinekko
Created April 21, 2024 13:11
Show Gist options
  • Save manekinekko/0aae4bbfdec4e47883f7c04310c40fa1 to your computer and use it in GitHub Desktop.
Save manekinekko/0aae4bbfdec4e47883f7c04310c40fa1 to your computer and use it in GitHub Desktop.
Mocking node:child_process.spawn() using Jest + TypeScript
import { Readable } from "stream";
const mockSpawn = jest.fn(() => {
return {
stdout: new Readable({
read() {
this.push("stout data"); // write mock data to stdout
this.push(null); // end stream
},
}),
stderr: new Readable({
read() {
this.push("error data"); // write mock data to stderr
this.push(null); // end stream
},
}),
on: jest.fn((event, callback: any) => {
if (event === "close") {
callback(0);
}
}),
};
});
jest.mock("node:child_process", () => {
return {
spawn: mockSpawn,
};
});
test("mock child_process.spawn", async () => {
// important: load implementation using dynamic import!
const { runExternalCommand } = await import("./index");
runExternalCommand(
(data: Buffer) => {
expect(data.toString('utf8')).toBe("stout data");
expect(mockSpawn).toHaveBeenCalled();
},
(error: Buffer) => {
expect(error.toString('utf8')).toBe("error data");
expect(mockSpawn).toHaveBeenCalled();
}
);
});
import { spawn } from "node:child_process";
export function runExternalCommand(onData: any, onError: any) {
const out = spawn("ls", ["-l"]);
out.stdout.on("data", onData);
out.stderr.on("data", onError);
}
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
{
"type": "module",
"scripts": {
"test": "jest"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/jest": "^29.5.12",
"jest": "^29.7.0",
"ts-jest": "^29.1.2",
"ts-node": "^10.9.2"
}
}
{
"compilerOptions": {
"esModuleInterop": true,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment