有一个我优雅关闭的例子:
function stopHandler() {
logger.info(`Stopping server on port ${settings.port} with pid ${process.pid} started`);
server.close(() => {
logger.info(`Server on port ${settings.port} with pid ${process.pid} stopped`);
process.exit();
});
setTimeout(() => {
logger.info(`Server on port ${settings.port} with pid ${process.pid} stop forcefully`);
process.exit();
}, settings.stopTimeout);
};
process.on("SIGTERM", stopHandler);
process.on("SIGINT", stopHandler);
Run Code Online (Sandbox Code Playgroud)
我如何用mocha测试这段代码?
rob*_*lep 13
这显然取决于你想要多大程度地测试你的代码,但这是一个开始的样板.
一些解释:
sinon存根两个函数:server.close()和process.exit().打桩他们指的不是调用这些功能,"伪功能"(存根)被调用,您可以断言,如果它得到调用;SIGINT测试,因为我发现mocha使用该信号来中止测试运行器.然而,由于双方SIGTERM并SIGINT使用完全相同的处理程序,那应该没问题;stopHandler应该被调用,做出你的断言,并在最后调用done回调告诉Mocha测试已经完成;代码:
const sinon = require('sinon');
// Load the module to test. This assumes it exports (at least)
// `server` and `settings`, because the test needs them.
let { server, settings } = require('./your-module');
// Don't call the stopHandler when exiting the test.
after(() => {
process.removeAllListeners('SIGTERM');
process.removeAllListeners('SIGINT');
})
describe('Signal handling', () => {
[ 'SIGTERM' /*, 'SIGINT' */ ].forEach(SIGNAL => {
describe(`${ SIGNAL }`, () => {
let sandbox, closeStub, exitStub;
beforeEach(() => {
sandbox = sinon.sandbox.create({ useFakeTimers : true });
closeStub = sandbox.stub(server, 'close');
exitStub = sandbox.stub(process, 'exit');
})
afterEach(() => {
sandbox.restore();
})
it(`should call 'server.close()' when receiving a ${ SIGNAL }`, done => {
process.once(SIGNAL, () => {
sinon.assert.calledOnce(closeStub);
done();
});
process.kill(process.pid, SIGNAL);
})
it(`should call 'process.exit()' after ${ settings.stopTimeout } seconds when receiving a ${ SIGNAL }`, done => {
process.once(SIGNAL, () => {
// It shouldn't have called `process.exit()` right after the signal was sent.
sinon.assert.notCalled(exitStub);
// Advance the clock to a bit after the timeout.
sandbox.clock.tick(settings.stopTimeout + 10);
// At this point, the timeout handler should have triggered, and
// `process.exit()` should have been called.
sinon.assert.calledOnce(exitStub);
// Done.
done();
});
process.kill(process.pid, SIGNAL);
})
})
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3149 次 |
| 最近记录: |