Last active
December 17, 2015 10:49
-
-
Save janv/5597831 to your computer and use it in GitHub Desktop.
Better async testing with jasmine.
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
'use strict'; | |
// Usage: | |
// Inside your examples call | |
// this.async(function(done){ | |
// someAsyncOperation(function callback(){ | |
// try { | |
// doStuff(); | |
// done() // Calling done without parameter causes test to pass | |
// } catch(e) { | |
// done(e); // Pass an error to done() if you want the test to fail | |
// } | |
// throw new Error(); // An error not passed to done will cause a timeout | |
// }) | |
// }) | |
jasmine.AsyncBlock = function (env, func, spec, timeoutError) { | |
this.timeoutError = timeoutError; | |
jasmine.Block.call(this, env, func, spec); | |
}; | |
jasmine.util.inherit(jasmine.AsyncBlock, jasmine.Block); | |
jasmine.AsyncBlock.prototype.execute = function (onComplete) { | |
var completed = false; | |
var self = this; | |
var timeout = setTimeout(function () { | |
self.spec.fail(self.timeoutError); | |
onComplete(); | |
completed = true; | |
}, 1000); | |
var done = function(error){ | |
if (!completed) { | |
if (error) self.spec.fail(error); | |
clearTimeout(timeout); | |
timeout = null; | |
onComplete(); | |
completed = true; | |
} | |
}; | |
if (!jasmine.CATCH_EXCEPTIONS) { | |
this.func.call(this.spec, done); | |
} else { | |
try { | |
this.func.call(this.spec, done); | |
} catch (e) { | |
this.spec.fail(e); | |
done(); | |
} | |
} | |
}; | |
jasmine.Spec.prototype.async = function (func) { | |
var timeoutError = new Error('Async Block Timeout'); // Create potential error it here so it has a more useful Stacktrace | |
var asyncBlock = new jasmine.AsyncBlock(this.env, func, this, timeoutError); | |
this.addToQueue(asyncBlock); | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment