Skip to content

Instantly share code, notes, and snippets.

@tzafrirben
Last active December 26, 2022 13:26
Show Gist options
  • Save tzafrirben/b1843d06f90ce62db45f5e3692462fea to your computer and use it in GitHub Desktop.
Save tzafrirben/b1843d06f90ce62db45f5e3692462fea to your computer and use it in GitHub Desktop.
Testing child process with Jest mock
jest.mock('child_process');
describe('Test execute commands in a spawn child process', () => {
test('execCommand should return command stdout/stderr', async () => {
// create a "fake" child process
const process = mockChildProcess();
// return the "fake" child process object when calling child_process.spawn
jest.spyOn(child_process, 'spawn').mockReturnValueOnce(process);
// note that execCommand returns a promise, so this fake child process was
// not spawned yet
const cmdExec = execCommand('no-such-command', '/path/to/nowhere');
// since we control the fake child process, we can emit the data events on
// stdout/stderr streams
process.stdout?.emit('data', 'Process stdout');
process.stderr?.emit('data', 'Process stderr');
// since we control the fake child process, we can end it
process.emit('close', 0);
// "execute" the command: spawn a child process and wait for it to end
const { stderr, stdout, code } = await cmdExec;
// validate the command output
expect(code).toEqual(0);
expect(stderr).toEqual('Process stderr');
expect(stdout).toEqual('Process stdout');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment