Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Last active July 15, 2016 18:04
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 karlpokus/67b7dd6c313bcaa1d423e1b8d6a4467f to your computer and use it in GitHub Desktop.
Save karlpokus/67b7dd6c313bcaa1d423e1b8d6a4467f to your computer and use it in GitHub Desktop.
How to test a single middeware with tape without a server running - in node or in browser
// This only works if you call - return next - in your middleware. Otherwise the cb (i.e next) won't return anything and the var will be undefined
// And you don't even need node - You can run it in a browser - Totally runtime agnostic
// Reference -> https://github.com/karlpokus/konstapel/blob/master/test/tests.js
var test = require('tape'),
m = require('module');
test('.usernameIsValid', function(t){
// mock req, res and next
var pass = m.usernameIsValid({user: {}}, null, function(){ return true }),
fail = m.usernameIsValid({}, null, function(err){ return err });
// test
t.equal(pass, true, 'calls next if req.user');
t.equal(fail instanceof Error, true, 'returns error if !req.user');
// you may even check new props set on req as JS passes objects by reference
// t.equal(req.user.data, 'much data', 'much data is created');
t.end();
});
@karlpokus
Copy link
Author

It's actually not necessary to return next to test middleware with tape.

m.usernameIsValid({user: {}}, null, function(){
  t.pass(); // or if error is passed -> t.err()
}),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment