Skip to content

Instantly share code, notes, and snippets.

@richmarr
Created December 2, 2013 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richmarr/7747115 to your computer and use it in GitHub Desktop.
Save richmarr/7747115 to your computer and use it in GitHub Desktop.
Example test that reads every Express route and verifies that every value pulled from `req.query`, `req.param` or `req.body` has been cleaned using `express-validator` and that each mother at least calls to `req.validationErrors()` to inspect what's wrong. This example assumes that all routes are exposed as a single package, e.g. `routes.user.ha…
/**
*/
var routes = require('../routes'),
assert = require('assert');
describe('routes', function(){
it("should exist", function(done){
assert(routes);
done();
});
var testMethodForCodeSmell = function( fn, name ){
var fnString = fn.toString();
describe(name,function(){
var validated = {},
validatedCount = 0,
accessed = {};
// Look through each function for parameters validated using express-validator
var matches = fnString.match(/req\.assert\(['"]([^'"]+)['"]/ig);
if ( matches ) matches.forEach(function(line){
var match = /req\.assert\(['"]([^'"]+)['"]/ig.exec(line);
if ( match && match.length > 1 ){
var paramName = match[1];
validatedCount++;
validated[paramName] = true; // mark this param name as being validated
}
});
it("should call req.validationErrors() to manage validation problems",function(done){
assert( validatedCount == 0 || fnString.indexOf("req.validationErrors()") > -1 );
done();
});
it("should validate every request parameter used using express-validator",function(done){
// Look through each function for parameters accessed from req.body, req.params, and req.query
matches = fnString.match(/req\.(body|query|param)\.([$a-z_][0-9a-z_$]*)/ig);
if ( matches ) matches.forEach(function(line){
var match = /req\.(body|query|param)\.([$a-z_][0-9a-z_$]*)/ig.exec(line);
if ( match && match.length > 2 ){
var paramName = match[2];
assert.equal( paramName+"="+(validated[paramName]?"":"not validated"), paramName+"=" );
}
});
done();
})
});
};
// Look through the nested request handlers in the `routes` module testing each one
var testRecursively = function( obj, name ){
for ( var prop in obj ){
if ( typeof obj[prop] == 'function' ) testMethodForCodeSmell( obj[prop], name+'.'+prop );
else if ( typeof obj[prop] == 'object' ) testRecursively( obj[prop], name+'.'+prop );
}
};
testRecursively(routes,'routes');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment