2013-10-08 38 views
1

我已经找到了一种方法来做到这一点,但我的直觉告诉我应该有一些更习惯性的做法。基本上,我不喜欢的是,我必须要求测试套件中的快速应用程序,这让我想知道是否存在竞赛状况。另外,我想知道如果我在几个这样的文件中运行几个测试套件会发生什么。测试快速应用程序API的正确方法?

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

我简化应用程序如下:

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(); 
       }); 
      }); 
    ... 
+2

我使用了一个名为supertest https://github.com/visionmedia/supertest的模块,它对此很有效。 – Brett

+1

如果您在应用中对端口进行硬编码,那么如果您需要这种灵活性,则无需在测试中将其导入。您可以考虑使用某种配置框架(如易于使用['config'](https://npmjs.org/package/config)),您可以在应用程序和测试中使用它。 – robertklep

+0

谢谢@Brett,我随你的建议去了,它对我的​​需求很好。 –

回答

2

摩卡让我们通过使用启动服务器一次任意数量的测试root Suite

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服务器(我们使用环境变量,使其运行在不同的端口比我们的开发服务器上):

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

(我们并不需要这里done()因为require是同步的。)这样,服务器就启动一次,不管有多少个不同的测试文件包含这个根级before函数。

然后我们还可以使用下面让我们可以保持开发者的服务器nodemon运行,同时运行测试:

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 
    }