gpt4 book ai didi

node.js - 如何编写测试以在 node.js 中正常关闭期间检查行为?

转载 作者:搜寻专家 更新时间:2023-11-01 00:10:23 25 4
gpt4 key购买 nike

有一个我优雅关机的例子:

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);

如何使用 mocha 测试此代码?

最佳答案

这显然取决于您想要测试代码的范围,但这里有一个样板文件。

一些解释:

  • 代码使用sinon stub 两个函数:server.close()process.exit()。 stub 意味着不是调用这些函数,而是调用“假函数”( stub ),并且您可以断言如果它被调用;
  • 我注释掉了 SIGINT 测试,因为我发现 mocha 使用该信号来中止测试运行器。但是,由于 SIGTERMSIGINT 使用完全相同的处理程序,所以应该没问题;
  • 信号传递是异步的,这意味着测试也必须是异步的。我为要测试的信号添加了一个“一次”信号处理程序,当进程发送信号时会调用它;那时,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);
})

})

})

})

关于node.js - 如何编写测试以在 node.js 中正常关闭期间检查行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40905239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com