Skip to content

Instantly share code, notes, and snippets.

@thurloat
Created November 19, 2012 20:12
Show Gist options
  • Save thurloat/4113577 to your computer and use it in GitHub Desktop.
Save thurloat/4113577 to your computer and use it in GitHub Desktop.
Jasmine Asynchronous Spec Functionality
@withAppIt = (desc, test) ->
spec = jasmine.getEnv().it desc
__app = null
__spy = new sinon.spy
__done = no
_NATIVE_ERR = window.onerror
# Perform the regular cleanup after a TestApplication test gets run. Restore
# ajax, and reset the DB.
spec.after ->
__app.restore()
__app.dataController.storage._resetDatabase (->), true
spec.runs ->
__app = new TestApplication @
# 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 builerplate by kicking off the
# session loading before the test starts, and wrapping the insides in a
# spec failer and reporter.
__app.onSessionLoaded ->
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."
describe "My Async Feature", ->
withAppIt "should perform async tests and report things correctly", (complete, app) ->
app.callAsyncMethod ->
(expect 1 + 1).toEqual 1
complete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment