node.js - 测试 Express response locals

标签 node.js testing express

我正在使用 Express.js 2.5.8。为了减少重复,我希望使用 dynamicHelper 将常用对象传递给 View ,而不是在每个路由中显式渲染它们。

我已经查看了源代码以了解在前往 View 的途中拦截本地人的方法,但没有太大的成功。我可以通过检查 app.dynamicViewHelpers 对象来确认它们的存在。但是,我想知道是否有实现此目标的较少依赖实现的方法。

理想的解决方案是不知道如何将值和对象传递给 View 。无论它们来自 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 的 View 系统。如果您使用的是 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'
});

关于node.js - 测试 Express response locals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455911/

相关文章:

javascript - 在 Javascript 中通过 WebSocket 的 HashMap

mysql - 验证 MySQL 驱动程序是否存在

c# - 通过 C# 测试测试你的数据库

node.js - Ember 和 Express : let Ember handle routes instead of Express?

javascript - 使用 Ajax、jquery、Node.js 和 Express POST 数据

node.js - 当用户离开 Meteor 和/或 Iron 路由器中的页面时如何捕捉?

javascript - 如何使用 express-validator 排除其他属性?

node.js - return 语句如何在 Node 中工作

node.js - Loopback 3 - 如何使用 datasources.json 中发送电子邮件的替代方法

python - 如何验证使用随机函数的正确性?