jQuery Trigger Event in AngularJS Karma Test

前端 未结 2 1835
别那么骄傲
别那么骄傲 2021-01-05 11:10

I\'m trying to test a new directive I\'m writing. However, I can\'t seem to get the keydown event to trigger with jQuery inside Karma/Jasmine.

Here is a simplified

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 11:43

    TLDR: load jQuery before AngularJS.

    At first, you may think that jQuery is not included. However, it is included. If it were not, the test would fail at $.Event.

    You have 2 dependencies on jQuery here:

    1. $.Event, a direct reference; and
    2. $, indirectly referenced by angular.element();

    When AngularJS is loaded, it looks for a previously loaded jQuery instance, and in case it does exist, it makes element just an alias to $. Otherwise it loads a reference to jqLite, which does not have a trigger method.

    So, I'm sure you do have jQuery loaded, but that does not mean AngularJS will use it. To do so, you must ensure jQuery is loaded (anywhere) before AngularJS.

    When angular.element() refers to jqLite, it would never call jQuery, even after jQuery is loaded. So you can only call methods defined on jqLite:

    angular.element(inputEl).triggerHandler(e);
    

    However, jqLite's triggerHandler would not perform event bubbling, it's not reliable to mock raising events. jQuery's trigger is way better.

    To use jQuery, do this on your HTML:

    
    
                                     
                  
提交回复
热议问题