Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active December 15, 2015 07:09
Show Gist options
  • Save henrik/5221144 to your computer and use it in GitHub Desktop.
Save henrik/5221144 to your computer and use it in GitHub Desktop.
Trigger jQuery DOM ready callbacks any time you like in mocha JS tests.
# Code:
$ -> # a.k.a. jQuery.ready ->
$("#hash-value-when-page-loaded").text(location.hash)
# Test:
location.hash = "foo"
fakeDomReady()
$("#hash-value-when-page-loaded").text().should.equal "#foo"
# Wrap jQuery.ready so we can trigger it in
# our mocha tests, which replace the body after
# the original ready event.
window.domReadyFunctions = []
window.fakeDomReady = ->
fn() for fn in domReadyFunctions
$.fn.oldReady = $.fn.ready
$.fn.ready = (fn) ->
domReadyFunctions.push(fn) if fn
$.fn.oldReady.apply(this, arguments)
@dualcyclone
Copy link

If you use Sinonjs, you can just do this...

sinon.stub($.fn, 'ready', function(fn) {
    fn();
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment