forked from aws/aws-cdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock-child_process.ts
64 lines (53 loc) · 1.83 KB
/
mock-child_process.ts
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
import * as child_process from 'child_process';
import * as events from 'events';
if (!(child_process as any).spawn.mockImplementationOnce) {
throw new Error('Call "jest.mock(\'child_process\');" at the top of the test file!');
}
export interface Invocation {
commandLine: string;
cwd?: string;
exitCode?: number;
stdout?: string;
/**
* Run this function as a side effect, if present
*/
sideEffect?: () => void;
}
export function mockSpawn(...invocations: Invocation[]) {
let mock = (child_process.spawn as any);
for (const _invocation of invocations) {
const invocation = _invocation; // Mirror into variable for closure
mock = mock.mockImplementationOnce((binary: string, options: child_process.SpawnOptions) => {
expect(binary).toEqual(invocation.commandLine);
if (invocation.cwd != null) {
expect(options.cwd).toBe(invocation.cwd);
}
if (invocation.sideEffect) {
invocation.sideEffect();
}
const child: any = new events.EventEmitter();
child.stdin = new events.EventEmitter();
child.stdin.write = jest.fn();
child.stdin.end = jest.fn();
child.stdout = new events.EventEmitter();
child.stderr = new events.EventEmitter();
if (invocation.stdout) {
mockEmit(child.stdout, 'data', invocation.stdout);
}
mockEmit(child, 'close', invocation.exitCode ?? 0);
mockEmit(child, 'exit', invocation.exitCode ?? 0);
return child;
});
}
mock.mockImplementation((binary: string, _options: any) => {
throw new Error(`Did not expect call of ${binary}`);
});
}
/**
* Must do this on the next tick, as emitter.emit() expects all listeners to have been attached already
*/
function mockEmit(emitter: events.EventEmitter, event: string, data: any) {
setImmediate(() => {
emitter.emit(event, data);
});
}