我的业务逻辑有一个条件,如果某个条件为真,则流程退出。这对于业务逻辑是正确的,但是对这种情况进行单元测试是一个问题,因为当我模拟条件的值时,测试过程本身就会退出,由于没有实际完成任何期望,所以最终我会打印错误。如何在不实际退出进程的情况下在茉莉花中模拟process.exit的功能?
为使问题更清楚,这是一些示例代码:
// 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();
}
我想从myFunction()调用返回并返回到单元测试,以便继续期望,但是由于process.exit(0)调用,测试完全中断了。
我该如何解决?
答案 0 :(得分:0)
尝试暗中监视process.exit
,所以它什么也不做:
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();
});
向您展示我的方式可能不起作用。在Google上进行快速搜索,了解如何对process.exit进行模拟/间谍操作,返回的结果是Jest的结果,而不是Jasmine的结果。