Create a gist now

Instantly share code, notes, and snippets.

jasmine-async.coffee
@asyncIt = (desc, test) ->
spec = jasmine.getEnv().it desc
__spy = new sinon.spy
__done = no
_NATIVE_ERR = window.onerror
spec.runs ->
# any async test must call this function in order to pass. This function is
# passed in as the first argument to the spec that gets run.
complete = (failed) ->
# restore the error handler to allow for the chrome console to catch the
# errors once everyone has been restored.
window.onerror = _NATIVE_ERR
__done = yes
if failed is undefined
__spy()
else
# continue bubbling the error to the error console
throw failed
# Fail specs when async internals fail.
window.onerror = (e, _, line) ->
er = new Error "#{e}"
er.stack = "Trace Unavailable, Check console for detailed message. (use @asyncBlock for async callbacks in tests)"
spec.fail er
complete e
# latch an async block function that will allow for better error reporting
# within tests themselves, as well as failing quickly when things go wrong
# by calling out to complete()
spec.asyncBlock = (f) ->
->
try
f.apply spec, arguments
catch e
spec.fail e
complete e
# start off the test suite, reduce test boilerplate by kicking off the
# session loading before the test starts, and wrapping the insides in a
# spec failer and reporter.
try
test.apply spec, [ complete, __app ]
catch e
spec.fail e
complete e
# wait for done to be set to `yes` (happens when complete() is called.
waitsFor -> __done
# finally, make sure the test ended up calling the complete() function. It
# times out after ~5 sec if none of the other error handling catches a
# problem with the test.
runs ->
(expect __spy).toHaveBeenCalled "Async Complete() never called."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment