Skip to content

Instantly share code, notes, and snippets.

@evantahler
Created October 29, 2012 03:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evantahler/3971280 to your computer and use it in GitHub Desktop.
Save evantahler/3971280 to your computer and use it in GitHub Desktop.
Domain Test for Mocha
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