Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stubbing process.exit with jest

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

like image 761
Nick Ginanto Avatar asked Sep 11 '17 04:09

Nick Ginanto


2 Answers

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() 
like image 80
Epic Eric Avatar answered Sep 17 '22 19:09

Epic Eric


For most of the global javascript object, I try to replace with my stub and restore after the test. Following works fine for me to mock process.

  describe('myFunc', () => {     it('should exit process on condition match', () => {       const realProcess = process;       const exitMock = jest.fn();        // We assign all properties of the "real process" to       // our "mock" process, otherwise, if "myFunc" relied       // on any of such properties (i.e `process.env.NODE_ENV`)       // it would crash with an error like:       // `TypeError: Cannot read property 'NODE_ENV' of undefined`.       global.process = { ...realProcess, exit: exitMock };        myFunc(true);       expect(exitMock).toHaveBeenCalledWith(ERROR_CODE);       global.process = realProcess;     });   }); 

This help to avoid running the real process.exit to avoid crashing the unit testing.

like image 25
joy Avatar answered Sep 16 '22 19:09

joy