【问题标题】:mocking process.exit in a jasmine test在茉莉花测试中模拟 process.exit
【发布时间】: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


    【解决方案1】:

    尝试监视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();
    });
    

    向您展示我的方式可能行不通。对如何模拟/监视 process.exit 进行快速谷歌搜索会返回 Jest 的结果,而不是 Jasmine 的结果。

    【讨论】:

    • 放一个间谍真的什么都没做吗?因为事情是我需要业务逻辑在那时退出。如果它只是返回,那将不起作用。
    • 是的,在上面放置一个间谍让它什么都不做。一旦你窥探,你就会失去实现细节,只知道它是否被调用,也许还有其他一些东西。
    • 忘记了这个。是的,我最终做了这个解决方案。这不是对业务逻辑的真正测试,但实际上单元测试应该只是验证是否调用了 process.exit。
    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多