Express+;摩卡:我怎么知道端口号?
我正在尝试学习节点和表达3与咖啡脚本。 我正在使用Mocha进行测试,并尝试引用端口号:Express+;摩卡:我怎么知道端口号?,express,mocha.js,Express,Mocha.js,我正在尝试学习节点和表达3与咖啡脚本。 我正在使用Mocha进行测试,并尝试引用端口号: describe "authentication", -> describe "GET /login", -> body = null before (done) -> options = uri: "http://localhost:#{app.get('port')}/login" request options, (err,
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'
TypeError:对象#没有方法“get”
有人能解释一下为什么它在测试中不起作用,以及我可以做些什么作为替代吗?你会感到困惑,因为你有一个
app.js
文件和模块中的一个变量,也称为app
,但你实际上还没有设置将app
变量作为模块导出公开。您可以这样做:
var app = exports.app = express();
然后在测试中,您可以使用require('../app').app.get('port')
(假设您的测试位于子目录中。根据需要调整相对路径)。您可能希望将app.js
重命名为server.js
,以减少混淆
但是,我建议使用一个专用的
config.js
模块来保存这种类型的配置数据。谢谢Peter!这个答案+额外的提示非常有用。