测试Express响应本地

时间:2013-03-16 23:24:44

标签: node.js testing 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

1 个答案:

答案 0 :(得分:0)

这是一个非常好的问题。我想最好的方法是使用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'
});
相关问题