【发布时间】:2020-09-02 23:27:32
【问题描述】:
我的业务逻辑有一个条件,如果某个条件为真,则流程退出。这对于业务逻辑是正确的,但是对这种情况进行单元测试是一个问题,因为当我模拟条件的值时,测试过程本身就退出了,因此我在最后打印了错误,因为没有任何期望真正完成。如何在 jasmine 中模拟 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) 调用,测试完全中断。
我该如何解决这个问题?
【问题讨论】:
标签: node.js jasmine jasmine-node