Created
September 2, 2022 23:46
-
-
Save evanhsu/f109cb813b3950275dcefea6c619736e to your computer and use it in GitHub Desktop.
Mimicking a ChildProcess in a nodeJS unit test
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
/** | |
* This is the function that we'll be testing. It takes a ChildProcess as | |
* an input arg, collects all the messages from the 'stderr' stream, then | |
* throws an Error with all the error messages concatenated once the | |
* ChildProcess ends | |
*/ | |
function collectChildProcessErrors(cp: ChildProcess) { | |
const errorMessages: string[] = []; | |
cp.on('stderr', (data: Buffer) => { | |
errorMessages.push(data.toString()); | |
}); | |
return new Promise<void>((resolve, reject) => { | |
cp.on('close', () => { | |
if (errorMessages.length > 0) { | |
resolve(); | |
// reject(new Error(errorMessages.join('; '))); | |
return; | |
} else { | |
resolve(); | |
return; | |
} | |
}); | |
}); | |
} | |
describe.('ChildProcess', () => { | |
it('mock a ChildProcess', async () => { | |
// This EventEmitter is masquerading as a ChildProcess by emitting events on the 'stderr' channel instead of writing to the 'stderr' stream | |
const childProcessWithErrors = new EventEmitter() as ChildProcess; | |
setTimeout(() => { | |
childProcessWithErrors.emit('stderr', 'This is error 1'); | |
childProcessWithErrors.emit('stderr', 'This is error 2'); | |
childProcessWithErrors.emit('close'); | |
}, 0); | |
try { | |
await collectChildProcessErrors(childProcessWithErrors); | |
assert.fail('Expected the function to throw an Error, but it didnt'); | |
} catch (error) { | |
expect(error.message).to.have.string('This is error 1'); | |
expect(error.message).to.have.string('This is error 2'); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment