Search code examples
javascripteventsjsunit

Test for Bound event using JSUnit?


How can I test to see that an event handler is bound to a node using JSUnit?

Here's what I have:

var mynode = document.getElementById( "mynode" );

assertNotNull( mynode );

MyLibrary.attachEvent( mynode, "click", function( ){ return true; } );

assertEquals( typeof mynode.onclick, typeof function( ){ return true; } );

But the type of mynode.onclick is, of course, object; while the typeof the function is..well...a function.

If I try just assertEquals( mynode.onclick, function( ){ return true; } ); the assertion also fails.

Any suggestions?


Solution

  • beware that the "onclick" property is not the same mechanism as addEventListener.

    in your exemple, the mynode.onclick property is probably equal to null because the MyLibrary.attachEvent is using the addEventListener (standard compliant) / attachEvent (IE < 9) method. Hence you test :

    typeof mynode.onclick = typeof null = "object"
    

    Now your problem is that when the DOM Level 2 Events specification was written they forget to give an accessor to the list of events that are currently registered on a node. So basically you cannot write the unit test that you try to implement.

    the DOM Level 3 Events specification (still in draft mode) addressed the problem in 2002 via a new property on the elements : eventListenerList

    Unfortunately, the current draft seems to have removed this property and i don't think you will find a browser implementing it.

    I could only find Firefox 3.6 implementing a getListenerInfoFor() method but it seems to be only available in chrome/XUL mode so it won't help.

    you could either

    • wait for eventListenerList to be implemented in all browsers ;-)
    • trust that MyLibrary correctly adds the event
    • add a fake event with testing code inside the callback function and dispatch a click event on the element

    I hope this will help you

    Jerome Wagner