自动化Jasmine-Node和express.js
我使用express.js创build了一个简单的Webapp,并且想用jasmine-node来testing它。 到目前为止工作正常,但我的问题是,我必须手动启动服务器,每次我可以运行我的testing。
你能帮我写一个spec-helper来运行服务器(与另一个端口,然后是我的开发者)只是为了testing,然后杀死它?
这就是我所做的:
我在我的节点项目的根目录中有一个server.js文件,用于设置节点应用程序服务器(使用express)并导出2个方法:
exports.start = function( config, readyCallback ) { if(!this.server) { this.server = app.listen( config.port, function() { console.log('Server running on port %d in %s mode', config.port, app.settings.env); // callback to call when the server is ready if(readyCallback) { readyCallback(); } }); } }; exports.close = function() { this.server.close(); };
app.js文件在这一点上会很简单:
var server = require('./server'); server.start( { port: 8000 } );
所以文件/文件夹的基本结构如下:
src app.js server.js
有了这种分离将允许您正常运行服务器 :
node src/app.js
.. 和/或从一个自定义的节点脚本 ,这可能是一个节点脚本(或一个jake / grunt /任何任务),执行您的testing,如下所示:
/** my-test-task.js */ // util that spawns a child process var spawn = require('child_process').spawn; // reference to our node application server var server = require('./path/to/server.js'); // starts the server server.start( { port: 8000 }, function() { // on server ready launch the jasmine-node process with your test file var jasmineNode = spawn('jasmine-node', [ '.path/to/test/file.js' ]); // logs process stdout/stderr to the console function logToConsole(data) { console.log(String(data)); } jasmineNode.stdout.on('data', logToConsole); jasmineNode.stderr.on('data', logToConsole); jasmineNode.on('exit', function(exitCode) { // when jasmine-node is done, shuts down the application server server.close(); } });
我使用摩卡 – 这是该死的类似的 – 但同样的原则应该适用:你可以尝试require
在你的app.js
文件在主要describe
内的“beforeEach”钩子。 这应该为你启动。
假设你使用了一些在server.js中调用app.listen()
代码,在每次运行时不要求文件,而只需要一次,然后有两个函数
startServer = -> app.listen(3000) stopServer = -> app.close()
那么你可以在beforeEach
和afterEach
使用这些
如果您想在开发过程中进一步自动化testing,则可以到terminal线路并执行
jasmine-node . --autotest
茉莉花然后将保持聆听项目中的每一个文件,每当你做出改变,它会告诉你的代码片断是否破坏你的任何testing;)