Created
October 29, 2012 03:18
-
-
Save evantahler/3971280 to your computer and use it in GitHub Desktop.
Domain Test for Mocha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var domain = require('domain'); | |
var should = require('should'); | |
////////////// | |
// Function // | |
////////////// | |
var add = function(a,b,callback){ | |
if(!isNumber(a)) { throw new Error(a + "is not a number"); } | |
if(!isNumber(b)) { throw new Error(b + "is not a number"); } | |
var response = a + b; | |
callback(response); | |
} | |
var isNumber = function(n) { | |
return !isNaN(parseFloat(n)) && isFinite(n); | |
} | |
////////////////////// | |
// domain container // | |
////////////////////// | |
var containWithDomain = function(a,b,callback){ | |
var wrapper = domain.create(); | |
wrapper.on("error", function(err){ | |
callback("caught by domain"); | |
}); | |
wrapper.run(function(){ | |
var response = add(a,b, function(response){ | |
callback(response); | |
}); | |
}); | |
} | |
//////////////////// | |
// normal running // | |
//////////////////// | |
// containWithDomain(1,{},function(response){ | |
// console.log(response); | |
// }) | |
/////////// | |
// TESTS // | |
/////////// | |
describe('test', function(){ | |
it('works normally', function(done){ | |
add(1,2,function(response){ | |
response.should.equal(3); | |
done(); | |
}) | |
}); | |
it('breaks normally', function(done){ | |
try{ | |
// this should thow an error, and does. | |
add(1,{},function(response){ | |
done(); | |
}) | |
}catch(e){ | |
String(e).should.eql("Error: [object Object]is not a number") | |
done(); | |
} | |
}); | |
it('works within the domain container', function(done){ | |
containWithDomain(1,2,function(response){ | |
response.should.equal(3); | |
done(); | |
}) | |
}); | |
it('should have errors caught by the domain and not raise the exception', function(done){ | |
containWithDomain(1,{},function(response){ | |
// this should not throw an error, but does :( | |
response.should.equal("caught by domain"); | |
done(); | |
}) | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment