node.jsjasminejasmine-node

mocking process.exit in a jasmine test


My business logic has a condition where if a certain condition is true, the process exits. This is correct for business logic, but unit testing this scenario is an issue because when I mock the value of the condition, the test process itself exits, and thus I get errors printed at the end since none of the expectations were actually completed. How can I mock the functionality of process.exit in jasmine, without actually exiting the process?

To make the problem clearer, here is some example code:

// Unit tests:

it('kills process when condition is false', async (done: DoneFn) => {
     let conditionSpy1 = spyOn(conditionApi, 'getConditionValue').and.returnValues(true, true, ..., false);
     let apiSpy1 = spyOn(api, 'method1').and....
     let apiSpy2 = spyOn(api2, 'method2').and...
     await myFunction();
     expect(api.method1).toHaveBeenCalled();
     expect(api2.method2).not.toHaveBeenCalled();
     done();
});
// business logic
async function myFunction() {

     const results = api.method1();
     for (const document of results) {
         const continueProcess = conditionApi.getConditionValue();
         if (!continueProcess) {
             console.log('received quit message. exiting job...');
             process.exit(0);
         }
         doStuff(document);
     }
     api2.method2();
}

I want to return from the myFunction() call and go back to the unit test so that the expectations continue, but because of the process.exit(0) call, the test cuts off completely.

How can I get around this?


Solution

  • Try spying on process.exit so it does nothing:

    it('kills process when condition is false', async (done: DoneFn) => {
         let conditionSpy1 = spyOn(conditionApi, 'getConditionValue').and.returnValues(true, true, ..., false);
         let apiSpy1 = spyOn(api, 'method1').and....
         let apiSpy2 = spyOn(api2, 'method2').and...
         spyOn(process, 'exit'); // add the line here so process.exit() does nothing but you can see if it has been called
         await myFunction();
         expect(api.method1).toHaveBeenCalled();
         expect(api2.method2).not.toHaveBeenCalled();
         done();
    });
    

    Showing you the way I have may not work. Doing a quick google search on how to mock/spy on process.exit returns results for Jest but not for Jasmine.