我正在尝试测试Angular指令,该指令根据按键事件返回true
或false
。我在输入标记内有ng-model
的UI中使用该指令。 HTML代码如下:
<div class="inline-middle-align set-margin ">
<input class="form-control" type="text" ng-model="addedRP.Offset" min="0" max="999" maxlength="3" style="width: 65px" placeholder="Offset" rp-Offset-Input-Validation-Directive required/>
</div>
指令代码是:
angular.module('helperModule')
.directive('rpOffsetInputValidationDirective', function (e) {
'use strict';
return {
require: 'ngModel',
link: function (scope, elem) {
elem.on('keypress', function (e) {
if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
}
};
});
我已经为它编写了一个测试,但它没有用。
it('should return true called on a keypress', function () {
$rootScope.happy = 10;
var ele = angular.element("<input ng-model='happy' rp-offset-input-validation-directive/>");
element = $compile(ele)($rootScope);
$rootScope.$digest();
$rootScope.e = $.Event('keypress');
e.which = 50;
$(ele[0]).trigger(e);
expect($rootScope.happy).toBe(2);
});