Last active
December 26, 2022 13:26
-
-
Save tzafrirben/b1843d06f90ce62db45f5e3692462fea to your computer and use it in GitHub Desktop.
Testing child process with Jest mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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