2012-11-24 90 views
2

我想用CoffeeScript學習節點和Express 3。 我使用摩卡做檢查,我試圖引用的端口號:Express + 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' 

可能有人請解釋爲什麼它不會在測試工作,我能做什麼來替代?

回答

1

你會感到困惑,因爲你有一個app.js文件,該模塊中的一個變量也被稱爲app,但是你還沒有真正設置一些東西來暴露app變量作爲模塊導出。你可以這樣做:

var app = exports.app = express(); 

然後在您的測試,你可以有require('../app').app.get('port')(假設你的測試是在一個子目錄中根據需要調整相對路徑)。您可能需要將app.js重命名爲server.js,以免混淆。

但是,我建議一個專用的config.js模塊來保存這種類型的配置數據。

+0

謝謝彼得!這個答案+其他提示非常有幫助。 – engmista