如何使用 mocha 测试 process.on()?
How to test process.on() using mocha?
如果这是一个幼稚的问题,我们深表歉意。我对 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
语句?
提前致谢。
您可以在 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')
})
})
如果这是一个幼稚的问题,我们深表歉意。我对 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
语句?
提前致谢。
您可以在 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')
})
})