【问题标题】:How to test process.on() using mocha?如何使用 mocha 测试 process.on()?
【发布时间】:2020-11-13 16:28:27
【问题描述】:

抱歉,如果这是一个幼稚的问题。我对 Typescript 和 Mocha 测试比较陌生。我想测试以下进程以增加代码覆盖率:

process.on('unhandledRejection', (reason, p) => {
    LoggingService.error(reason, 'unhandledRejection', 'Unhandled Rejection at:');
});

process.on('uncaughtException', (error) => {
    LoggingService.error(error, 'unhandledRejection', 'Caught exception: ');
});

process.on('warning', (warning) => {
    LoggingService.info('Warning, Message: ' + warning.message + ' Stack: ' + warning.stack, 'warning');
});

process.on('exit', (code) => {
    LoggingService.error(null, 'NodeJs Exit', `Node.js process is about to exit with code: ${code}`);
});

如何在 mocha 中为进程编写测试?特别是,如果我想为unhandledRejection, uncaughtException, warning, exit 模拟process.on,我将如何做到这一点以及我会期待什么,因为这些进程没有return 语句?

提前致谢。

【问题讨论】:

    标签: node.js typescript mocha.js


    【解决方案1】:

    您可以在process 对象上发出事件来测试事件处理程序。 并且您可以监视 LoggingService 对象,以检查使用 sinon 之类的库是否使用预期参数调用了方法。

    这个基于console.log 的例子展示了这个想法:

    const sinon = require('sinon');
    
    // This event handler is what we are going to test 
    process.on('warning', () => {
      console.log('received warning');
    });
    
    describe('process', () => {
      it('should handle "warning" event', (done) => {
        const spy = sinon.spy(console, 'log');
    
        process.on('warning', () => {
          sinon.assert.calledWith(spy, 'received warning')
          done()
        });
    
        process.emit('warning')
      })
    })
    

    【讨论】:

    • 我无法测试它。它说Argument of type '"warning"' is not assignable to parameter of type '"disconnect"'.ts(2345)。仅供参考:我正在使用 Hapi.js 和 typescript 来构建其余的 API。
    • 我解决了上述问题,但不适用于uncaughtException。它未能通过单元测试用例process.emit("uncaughtException", new Error("raise error"));
    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 2013-02-10
    • 1970-01-01
    • 2012-05-26
    • 2016-04-22
    • 2013-04-24
    • 2017-02-04
    相关资源
    最近更新 更多