正确的方式来testing快速应用程序API?

我已经find了一个办法,但我的直觉告诉我应该有一些更习惯性的做法。 基本上我不喜欢的是,我必须要求在testing套件中的快速应用程序,这让我想知道是否有一个种族条件正在进行。 另外,我想知道如果我在几个这样的文件中运行几个testing套件会发生什么。

任何人都知道更清洁的解决

我简化的应用程序如下所示:

app.js

app = module.exports = express() ... http.createServer(app).listen(app.get('port'), function(){ console.log('app listening'); }); 

test.js

 var request = require('superagent'); var assert = require('assert'); var app = require('../app'); var port = app.get('port'); var rootUrl = 'localhost:'+port; describe('API tests', function(){ describe('/ (root url)', function(){ it('should return a 200 statuscode', function(done){ request.get(rootUrl).end(function(res){ assert.equal(200, res.status); done(); }); }); ... 

我使用了一个名为supertest github.com/visionmedia/supertest的模块,它可以很好地工作。

摩卡让我们使用root Suite启动一次服务器进行任意次数的testing:

You may also pick any file and add "root" level hooks, for example add beforeEach() outside of describe()s then the callback will run before any test-case regardless of the file its in. This is because Mocha has a root Suite with no name.

我们使用它来启动Express服务器一次(并且我们使用一个环境variables,以便它运行在与我们的开发服务器不同的端口上):

 before(function () { process.env.NODE_ENV = 'test'; require('../../app.js'); }); 

(这里我们不需要done() ,因为require是同步的。)这样,服务器启动一次,不pipe这个根级有多less个不同的testing文件包含在这个函数before

然后,我们还使用以下内容,以便我们可以使开发人员的服务器与nodemon一起运行,并同时运行testing:

  if (process.env.NODE_ENV === 'test') { port = process.env.PORT || 3500; // Used by Heroku and http on localhost process.env.PORT = process.env.PORT || 4500; // Used by https on localhost } else { port = process.env.PORT || 3000; // Used by Heroku and http on localhost process.env.PORT = process.env.PORT || 4000; // Used by https on localhost }