gpt4 book ai didi

node.js - 测试 Express response locals

转载 作者:搜寻专家 更新时间:2023-11-01 00:08:52 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com