I dove into the world of JavaScript a few weeks ago. I use Angular, and I test my code with Karma and Jasmine. I have an angular directive I'm having trouble testing.
I have an angular directive that's meant to be used with <input>
box. The directive modifies the input box so it only accepts number as input. Here's 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'd use it in html like so:
<div>
Numbers only: <input number-only ng-required="true"
ng-model="myNumber" type="text" maxlength="3"
placeholder="NNN">
</div>
I'd like to test that the directive gets wired correctly, and it successfully filters out non-number input. If I were to type in "a1b2c3", the input box should have "123".
I've tried many different ways of entering a string to the input box and checking a value (of the input box, angular model, etc.) afterwards, but none of them worked so far.
Following test is an example of my many trials:
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);
};
});
I even tried writing e2e tests to simulate user input. I've also tried extracting my event handler function from the HTML element, and unit test the function. None worked so far.
How should I best test my angular directive?