Testing bound jQuery events
I’ve been using Jasmine, along with velesin’s jasmine-jquery, to test all of my JavaScript work recently. jasmine-jquery provides some really handy matchers, but one thing that’s missing is the ability to test whether an element has a bound event.
I’ve come up with the following matcher to do just that:
Use it like so: expect($('input#foo')).toHaveEvent('keyup');
I’d be interested to hear of any thoughts or improvements. Likewise, I’ve started work on testing for events attached using $.fn.live()
. These are handled a bit differently, since live events aren’t actually bound to the selected element. Instead they sit there, bound to the document
, listening for the event to bubble up the DOM tree.
So: expect($('input#bar')).toHaveLive('focus');
Again, any improvements or thoughts are welcome.
You can make these matchers available by using this.addMatchers
.