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 version of the test :
'use strict';
describe('', function() {
var $compile;
var $scope;
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
}));
describe('Getting Trigger To Work', function() {
it('Should Trigger a KeyDown Event', function() {
var el = $compile('<form name="testing"><input id="field1" name="testfield" ng-model="result" type="text" ng-minlength="5" ng-maxlength="50"/></form>')($scope);
console.log(el);
var inputEl = el.find('input');
console.log(inputEl);
var e = $.Event('keydown');
e.which = 65;
inputEl.trigger(e);
});
});
});
My karma config includes AngularJS and jQuery. Here's that section:
//
files: [
'lib/angular.js',
'lib/angular-mocks.js',
'lib/jquery-1.10.2.min.js',
'test/**/*Spec.js'
],
When I run the test, I get an error that my input element has no trigger method :
INFO [watcher]: Changed file "/Volumes/Macintosh HD/dev_libraries/val-on-timeout/test/valOnTimeoutSpec.js".
LOG: Object{0: <form name="testing" class="ng-scope ng-pristine ng-valid"><input id="field1" name="testfield" ng-model="result" type="text" ng-minlength="5" ng-maxlength="50" class="ng-pristine ng-valid"></form>, length: 1}
LOG: Object{0: <input id="field1" name="testfield" ng-model="result" type="text" ng-minlength="5" ng-maxlength="50" class="ng-pristine ng-valid">, length: 1}
Chrome 32.0.1700 (Mac OS X 10.8.5) testing valOnTimeout Should load FAILED
TypeError: Object [object Object] has no method 'trigger'
at null.<anonymous> (/Volumes/Macintosh HD/dev_libraries/val-on-timeout/test/valOnTimeoutSpec.js:79:21)
Chrome 32.0.1700 (Mac OS X 10.8.5): Executed 1 of 1 (1 FAILED) ERROR (0.327 secs / 0.033 secs)
At first, you may think that jQuery is not included. However, it is included. If it were not, the test would fail at $.Event
.
Suggestions on getting the keydown event to work on the input?
I hope this works
var e = $.Event('keydown');
e.which = 65;
$(inputEl).trigger(e); // convert inputEl into a jQuery object first
// OR
angular.element(inputEl).triggerHandler(e); // angular.element uses triggerHandler instead of trigger to trigger events
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With