我已经在 Locomotive 的 github 上回答了这个问题,但是我想在这里分享以获得一些反馈,比如以更好的方式、更清洁的方式或您可能拥有的任何其他输入。
我需要 OAuth2 环境中的多台服务器(身份验证、资源、仪表板..),其中大部分是基于 Locomotive 框架的。
我喜欢功能测试,因为它们最能代表基于 OAuth2 的身份验证,而不是将我的测试集中在身份验证令牌可能不能最好地代表用户的资源服务上。
这是我为启动机车服务器而设计的设置:
对于您的测试,请说test/util.severs.js
var fork = require('child_process').fork,
async = require("async");
var authApp;
var serverStatus = [];
var start = function(done) {
authApp = fork( __dirname + '/../../authorization/server.js');
serverStatus.push(function(callback){
authApp.on('message', function(m){
//console.log('[AUTHORIZATION] SENT MESSAGE: ', m);
if (m.status == 'listening') return callback();
});
});
// add others servers if you swing that way!
async.parallel(serverStatus, function(){
done();
});
}
var stop = function(done) {
authApp.kill();
done();
}
module.exports = {
start: start,
stop: stop
};
请注意,我在这里使用异步,因为我正在使用多台服务器(环境在 OAuth2 中,需要启动许多服务器(IE 资源,仪表板...)),如果您将拥有的只是一台服务器,请忽略异步.
在您的 Mocha 测试中需要上述文件并执行
servers = require('./util/servers');
...
before(servers.start);
// tests away!!!
after(servers.stop);
然后在我的每个 locomotive-project/server.js 我执行以下操作...
// if being started as a parent process, send() won't exist, simply define
// it as console.log or what ever other thing you do with logging stuff.
if (process.send === undefined){
process.send = function(msg){
console.log("status: ", msg.status);
};
}
process.send({status: 'starting'});
...
app.boot(function(err) {
if (err) {
process.send({status: 'error', message: err});
return process.exit(-1);
} else {
// notify any parents (fork()) that we are ready to start processing requests
process.send({status: 'listening'});
}
});
在此处使用 Locomotive 0.4.x,根据您的版本可能会有所不同。
这是最好的方法吗?理想情况下,我想将其转移到 Grunt,即测试服务器初始化(这是相当庞大的,因为我们将大量数据构建到测试数据库中),然后可以运行功能测试。所以想知道是否有人研究过 grunt 来代替 Mocha 中的 before() 任务。