0

如何使用 vows.js 干净地测试以下函数,该函数旨在基于对象层次结构向 express.js 应用程序添加路由,而不会破坏誓言对主题和誓言的分离?

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");
                        });

应该调用。

4

1 回答 1

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);
于 2013-08-07T16:39:51.900 回答