Skip to content

Instantly share code, notes, and snippets.

@tsmx
Last active August 9, 2020 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsmx/8985c4f96f0a75fe986bf066226d2ce2 to your computer and use it in GitHub Desktop.
Save tsmx/8985c4f96f0a75fe986bf066226d2ce2 to your computer and use it in GitHub Desktop.
Jest: properly test a function branch ending in process.exit, e.g. in a CLI app
const myFunc = function (condition) {
console.log('before');
if (condition) {
process.exit(-1);
}
console.log('after');
}
describe('jest-process-exit test suite', () => {
it('tests myFunc with process.exit', async (done) => {
const mockExit = jest.spyOn(process, 'exit')
.mockImplementation((number) => { throw new Error('process.exit: ' + number); });
expect(() => {
myFunc(true);
}).toThrow();
expect(mockExit).toHaveBeenCalledWith(-1);
mockExit.mockRestore();
done();
});
});
// for more details and a full working example see: https://github.com/tsmx/jest-process-exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment