我已经在node.js中创建了一个small example application,此处包含单元测试和验收测试
单元测试和验收测试均在Mocha流程中运行。验收测试从分叉过程开始,基本上是在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上运行,但是在服务器上却并非总是如此,因此我增加了延迟-等待一段时间,直到服务器启动。 根据经验,我发现1s就足够了,.5s不够。 但是,我想知道应该怎么做才能确保服务器是。
Are there any solutions to run server, execute the tests and shutdown the server that works on Linux, Windows, docker and outside of it?
答案 0 :(得分:1)
how to communicate between fork processes有很好的帮助。
想法是从孩子那里发送一条消息,告诉父亲(我准备好了!)。然后爸爸会继续工作。
示例:
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");
}