Search code examples
javascriptjqueryunit-testingqunit

How can I trigger a native Javascript event from a QUnit test?


I'm working on a Javascript library that does not depend on jQuery, though I have jQuery and QUnit available in my tests. In the library, I attach an event to an element the way jQuery does:

if (document.addEventListener) {
  tab.addEventListener('click', MyModule.show, false);
} else if (document.attachEvent) {
  tab.attachEvent('click', MyModule.show);
}

I tried calling $('#tab').click(); in my QUnit test, but it doesn't cause my event handler to be called.


Solution

  • jQuery has its own event registration system, which is separate from the DOM's event registration. When we call $(something).click(), all registered jQuery handlers and the registered onclick handler will fire, but nothing else would. For example,

    document.body.addEventListener('click', function() { alert('event') }, false);
    document.body.onclick = function() { alert('onclick'); };      
    
    $('body').click(); // alerts "onclick"
    

    If you call document.body.onclick(), then only the second event will fire and alert "onclick". To get both events to fire, create an event object and dispatch it for the element in question - body in this case. You can find an example here. Unsurprisingly, IE uses a different mechanism to do the same and you need to call fireEvent.

    Here's a non cross-browser example for modern browsers (taken from the MDC article above),

    var clickEvent = document.createEvent('MouseEvents');
    clickEvent.initMouseEvent('click', true, true, window,
        0, 0, 0, 0, 0, false, false, false, false, 0, null);
    
    document.body.dispatchEvent(clickEvent);