stubbing process.exit with jest

Nick Ginanto picture Nick Ginanto · Sep 11, 2017 · Viewed 13.7k times · Source

I have code that does something like

 function myFunc(condition){
  if(condition){
    process.exit(ERROR_CODE)
  }
 }

How can I test this in Jest? Overwriting exit in process with jest.fn() and returning it back after the test doesn't work, since the process exits

Answer

Epic Eric picture Epic Eric · Jul 20, 2018

The other suggestions in this thread would cause errors on my end, where any tests with process.exit would run indefinitely. The following option worked for me on TypeScript, but it should work on JavaScript as well:

const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
myFunc(condition);
expect(mockExit).toHaveBeenCalledWith(ERROR_CODE);

The catch is that simply using spyOn meant that the original process.exit() function was still called, ending the process thread and hanging tests. Using mockImplementation at the end replaces the function body with the provided function (which is empty in my example).

This trick is also useful for tests that print to, say, stdout. For example:

const println = (text: string) => { process.stdout.write(text + '\n'); };
const mockStdout = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});
println('This is a text.');
expect(mockStdout).toHaveBeenCalledWith('This is a text.\n');

This will let you test printed values, and have the added benefit of not messing up CLI console output with random linebreaks.


Just one note: As with any "jest.spyOn" call, regardless of using mock implementation or not, you need to restore it later on in order to avoid weird side-effects of lingering mocks. As such, remember to call the two following functions at the end of the current test case:

mockExit.mockRestore()
mockStdout.mockRestore()