如何使用vows.js干净地测试以下用于基于对象层次结构向express.js app添加路由的函数,而不会破坏主题和誓言的誓言分离?
var addRoutes = function(routeObject, app, path) {
var httpVerbs = ['get', 'post', 'put', 'delete'];
path = path || '';
for(var property in routeObject){
var routesAdded = false;
for (var verbIndex in httpVerbs) {
var verb = httpVerbs[verbIndex];
var completePath, handler;
if (property === verb) {
if (typeof(routeObject[verb]) === 'function') {
handler = routeObject[verb];
completePath = path;
} else {
handler = routeObject[verb].handler;
completePath = path + (routeObject[verb].params || '');
}
app[verb](completePath, handler);
routesAdded = true;
}
}
if (!routesAdded) {
addRoutes(routeObject[property], app, path + '/' + property);
}
}
};
测试应确认在app对象上调用与http谓词对应的函数。例如如果routeObject是:
{
tracker: {
message: {
get: {
handler: function (req, res) {
res.send("respond with a resource");
}
}
}
}
}
然后
app.get('/tracker/message', function (req, res) {
res.send("respond with a resource");
});
应该叫。
答案 0 :(得分:0)
这样的事情应该有效:
var assert = require('assert'),
request = require('request');
var verbs = ['get', 'post', 'put', 'delete'],
app = require('your/app.js'),
port = 8080;
//
// Your route would look something like this
//
var example = {
tracker: {
message: {
get: {
status: 200,
body: 'respond with a resource'
}
}
}
};
function testRoutes(suite, route, app, path) {
path = path || '/';
Object.keys(route).forEach(function (key) {
if (~verbs.indexOf(key)) {
return testRoutes(suite, route[key], app, [path, key].join('/'));
}
var test = [key, path].join(' ');
suite[test] = {
topic: function () {
request({
method: key,
uri: 'http://localhost' + port + path
}, this.callback);
},
'should respond correctly': function (err, res, body) {
assert.isNull(err);
assert.equal(res.statusCode, route[key].status);
assert.equal(body, route[key].body);
}
}
});
return suite;
}
var suite = vows.describe('api');
testRoutes(suite, example, app);
suite.export(module);