Express+Mocha:如何获取端口号



我正在尝试用CoffeeScript学习node和Express3。我正在使用Mocha进行测试,并试图参考端口号:

describe "authentication", ->
describe "GET /login", ->
body = null
before (done) ->
options =
uri: "http://localhost:#{app.get('port')}/login"
request options, (err, response, _body) ->
body = _body
done()
it "has title", ->
assert.hasTag body, '//head/title', 'Demo app - Login'

我之所以使用它,是因为它也是app.js文件中使用的:

require('coffee-script');
var express = require('express')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options',{layout:false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
app.locals.pretty = true;
});
app.configure('test', function(){
app.set('port', 3001);
});
require('./apps/authentication/routes')(app)
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});

然而,当我运行这个测试时,我得到了错误:

TypeError: Object #<Object> has no method 'get'

有人能解释一下为什么它在测试中不起作用,以及我可以做些什么作为替代吗?

您会感到困惑,因为您有一个app.js文件和该模块中的一个也称为app的变量,但您实际上还没有设置将app变量作为模块导出公开。你可以这样做:

var app = exports.app = express();

然后在你的测试中你可以有require('../app').app.get('port')(假设你的测试在一个子目录中。根据需要调整相对路径)。您可能希望将app.js重命名为server.js,以减少混淆。

但是,我建议使用一个专用的config.js模块来保存这种类型的配置数据。

最新更新