使用Mocha和Grunt在Sails.js中运行functiontesting时的竞态条件

我正在使用Sails v0.10.x,并且在运行我的functiontesting时遇到问题。

testing/ bootstrap.test.js

// force the test environment to 'test' process.env.NODE_ENV = 'test'; var Sails = require('sails'); // use zombie.js as headless browser var Browser = require('zombie'); // Global before hook before(function(done) { var self = this; // Lift Sails and start the server Sails.lift({ log: { level: 'error' }, }, function(err, sails) { // initialize the browser using the same port as the test application self.browser = new Browser({ site: 'http://localhost:1337', debug: false }); done(err, sails); }); }); // Global after hook after(function(done) { Sails.lower(done); this.browser.close(); }); 

问题是Sails.lift触发默认的Grunt任务运行。 这项任务之一是清除公用文件夹,然后复制资产。

我的问题是我的functiontesting正在运行,而这种复制仍在发生。 这意味着当我的无头浏览器正在请求静态资产时,我会得到大量的404错误(并且testing失败)。

我猜测可能有几个解决scheme

  • 添加一个消息“帆升降机”命令,不清除公用文件夹(这可能会导致部署后运行testing时会出现问题?)
  • 在启动我的无头浏览器之前增加了一个超时后的超时(虽然这看起来很诡异)
  • 某种callback/事件(不知道这是可能的吗?)

其他人提出了什么解决scheme来解决这个问题?

您可以尝试在生产模式下解除应用程序:

 Sails.lift({ log: { level: 'error' }, environment: 'production' }, function(err, sails) {...} 

在生产模式下,在所有Grunt任务完成之前,Sails不能完成提升。

如果这不是您的select(因为您需要testing在具有特定设置的不同环境中运行),则可以监听hook:grunt:done事件,直到收到它为止,才开始testing。 您需要closures您正在运行testing的环境的“监视”任务(否则Grunt将永远不会完成!)。 这意味着如果你想保持你的开发环境的“监视”,你需要在不同的环境下运行testing(这是一个好主意)。 所以首先,在tasks / register / default.js中

 module.exports = function (grunt) { var tasks = ['compileAssets', 'linkAssets']; if (process.env.NODE_ENV !== 'test') {tasks.push('watch');} grunt.registerTask('default', tasks); }; 

然后在你的testing中:

 var async = require('async'); async.parallel({ // Set up a listener for grunt finish listenForGrunt: function(cb) {sails.on('hook:grunt:done', cb);}, // Lift sails liftSails: function(cb) { Sails.lift({ log: { level: 'error' }, }, function(err, sails) { self.browser = new Browser({ site: 'http://localhost:1337', debug: false }); cb(err, sails); }); } }, done); 

运行你的testingNODE_ENV=test mocha ,或者更好的在你的package.json scripts下,把:

 "test": "NODE_ENV=test mocha" 

所以你可以运行npm test

这将确保在Sails解除 Grunt完成之前不会调用完成。