【问题标题】:Express + Mocha: How do I get the port number?Express + Mocha:如何获取端口号?
【发布时间】:2012-11-24 18:22:13
【问题描述】:

我正在尝试使用 CoffeeScript 学习 node 和 Express 3。 我正在使用 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'

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

【问题讨论】:

    标签: express mocha.js


    【解决方案1】:

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

    var app = exports.app = express();
    

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

    不过,我建议使用专用的config.js 模块来保存此类配置数据。

    【讨论】:

    • 谢谢彼得!这个答案+其他提示非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2012-06-28
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多