【问题标题】:Testing for Express response locals测试快速响应本地人
【发布时间】:2013-03-16 23:24:44
【问题描述】:

我正在使用 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

【问题讨论】:

  • 您能否提供一个小示例场景来说明您正在尝试做什么?我不明白为什么你不能写一些东西来包装包含附加数据的模板插件。
  • @Brad 我不确定你的建议是什么。这是测试的一部分,还是生产代码的一部分?
  • 我现在明白了。不知何故,在我第一次阅读您的问题时,我完全错过了“测试”部分。

标签: node.js testing express


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2014-07-13
    • 2014-04-17
    • 2020-12-27
    • 2018-05-02
    相关资源
    最近更新 更多