测试Express响应本地变量



我使用Express.js 2.5.8。为了减少重复,我希望使用dynamicHelper将常用对象传递给视图,而不需要在每个路由中显式呈现它们。

我已经查看了源代码,寻找在局部变量到达视图的途中拦截它们的方法,但没有太大的成功。我可以通过检查app.dynamicViewHelpers对象来确认它们的存在。但是,我想知道是否有一种较少依赖于实现的方法来实现这一点。

理想的解决方案是不知道值和对象是如何传递给视图的。无论它们来自viewHelper、中间件还是路由本身,测试都应该通过,不需要修改。无论如何,这是理想状态。我将接受其他方法。

我要测试的一个松散的例子:

app.dynamicHelpers({
  example : function(req, res){
    return "Example Value";
  }
});
app.get('/example', function(req, res){
  res.render('example-view', {
    sample : "Sample Value"
  });
});
// test that example === "Example Value" in the view
// test that sample === "Sample Value" in the view

这是一个非常好的问题。我想最好的方法就是进入Express的视图系统。如果您使用的是Express 2,它可能看起来像这样:

var express = require('express');
var app = express.createServer();
express.view.compile = function (view, cache, cid, options) {
  // This is where you get the options as passed to the view
  console.log(options);
  return {
    fn: function () {}
  };
};
app.locals({
  passed_via_locals: 'value'
});
app.get('/', function (req, res, next) {
  res.render('index', {
    passed_in_render: 'value',
    layout: false
  });
});
app.listen('./socket');
var http = require('http');
http.get({socketPath: './socket'});

在Express 3中,这变得容易多了:

var express = require('express');
var app = new express();
function View() {
  this.path = true;
};
View.prototype.render = function(options, cb) {
  // This is where you get the options as passed to the view
  console.log(options);
};
app.set('view', View);
app.locals({
  passed_via_locals: 'value'
});
app.render('index', {
  passed_in_render: 'value'
});

最新更新