How to get grunt.js to start an express app for testing

放肆的年华 提交于 2019-12-03 12:50:01

If you check grunt-express which is a plugin for express web-server tasks via grunt.

express-keepalive

Note that this server only runs as long as grunt is running. Once grunt's tasks have completed, the web server stops. This behavior can be changed by appending a express-keepalive task at the end of your task list like so

grunt.registerTask('myServer', ['express', 'express-keepalive']);
Now when you run grunt myServer, your express server will be kept alive until you manually terminate it.

Such feature can also be enabled ad-hoc by running the task like grunt express express-keepalive.

This design gives you the flexibility to use grunt-express in conjunction with another task that is run immediately afterwards, like the grunt-contrib-qunit plugin qunit task. If we force express task to be always async, such use case can no longer happen.

From the guide grunt-contrib-qunit package is used to run QUnit unit tests in a headless PhantomJS instance. Also mind the last line, if you force express to be always async it would be of no use.

npm link for grunt-express.

I'm not sure if I understand your problem correctly, but probably this helps:

Do you know about Grunt's async function? For some time I used the following approach to start (and stop) my Express app. I used it with watch, so it automatically restarted on save. In this case you have to set watch's nospawn option to true.

var server = null;
grunt.registerTask('server', 'Start server', function() {
  var done = this.async();
  if (server !== null) {
    server.close();
    clearCache();
  }
  var app = require('./my-express-app.js');
  server = http.createServer(app).listen(app.get('port'), function(){
    done();
  });
});

function clearCache() {
  for (key in require.cache) {
    if (key.indexOf(__dirname + '/node_modules/') == -1) {
      delete require.cache[key];
    }
  }
}

It is ugly because of this require-cache-hack. However, it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!