我创建了一个 small example application在 Node.js 中进行单元测试和验收测试
单元测试和验收测试都在 mocha 进程内运行。验收测试从 fork 进程开始,基本上在 before() 方法上运行服务器。 after() 方法停止进程并
before((initialized) => {
console.log('before script');
serverProcess = child_process.fork('server.js');
serverProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
setTimeout(() => {
console.log('1s elapsed');
initialized();
}, 1000);
代码没有任何延迟,可以在我本地的 gitlab-runner 上运行,但是在服务器上情况并非总是如此,因此我添加了延迟 - 等待一段时间,直到服务器启动。 根据经验,我发现 1 秒就足够了,而 0.5 秒则不够。 但是,我想知道我应该做什么来确保服务器正常。
Are there any solutions to run server, execute the tests and shutdown the server that works on Linux, Windows, docker and outside of it?
最佳答案
关于how to communicate between fork processes有一个很好的帮助.
这个想法是从 child 那里发送一条消息,告诉它的爸爸(我准备好了!)。然后爸爸就会继续工作。
示例:
before((initialized) => {
serverProcess = child_process.fork('server.js');
serverProcess.on('close', function(code) {
console.log('child process exited with code ' + code);
});
serverProcess.on('close', function(code) {
console.log('child process exited with code ' + code);
});
// We add a backup plan. If it takes too long to launch, throw
const timeout = setTimeout(() => {
initialized(new Error('tiemout');
}, 30000);
// Cait for the child to send a message to us
serverProcess.on('message', function(str) {
if (str === 'init done') {
clearTimeout(timeout);
// server.js got successfully initialized
initialized();
}
});
});
<小时/>
// To add inside of your server.js listen
if (process.send) {
process.send("init done");
}
关于node.js - 如何以编程方式等待进程启动端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55833412/