A few weeks ago, I entered the world of JavaScript. I am using Angular and I am testing my code with Karma and Jasmine. I have an angular directive. I have problems with testing.
I have an angular directive that is intended to be used with <input>. The directive modifies the input field so that it accepts only a number. Here is a simplified version of the code:
var testDirective = angular.module('testDirectiveApp', []);
testDirective.directive('numberOnly', function() {
return {
restrict: 'A',
link: function (scope, element) {
element.on('keydown', function (event) {
var k = event.keyCode;
if (48 <= k && k <= 57) {
return true;
}
event.preventDefault();
return false;
});
}
};
});
I would use it in html like this:
<div>
Numbers only: <input number-only ng-required="true"
ng-model="myNumber" type="text" maxlength="3"
placeholder="NNN">
</div>
I would like to check if the directive is connected correctly, and it successfully filters out non-numeric input. If I were to enter "a1b2c3", the input field should have "123".
I tried many different ways to enter a string in the input field and check the value (input windows, angular model, etc.), but none of them have worked so far.
- :
describe('numberOnly', function() {
'use strict';
var scope, element;
beforeEach(module('testDirectiveApp'));
beforeEach(inject(function($compile, $rootScope) {
scope = $rootScope.$new();
scope.testInput = "";
element = angular.element('<input number-only ng-model="testInput" type="text">');
$compile(element)(scope);
scope.$digest();
}));
it('should accept number input', function() {
triggerKeyDown(element, 49);
expect(scope.testInput).toBe("1");
});
var triggerKeyDown = function (element, keyCode) {
var e = $.Event("keydown");
e.which = keyCode;
e.keyCode = keyCode;
$(element).trigger(e);
};
});
e2e, . HTML unit test . .
angular?