我有以下指令,它工作得很好,现在我需要对它进行单元测试,
(() => {
angular
.module('app.utilities')
.directive('allowPattern', allowPatternDirective);
function allowPatternDirective () {
return {
restrict: 'A',
compile () {
return (scope, element, attrs) => {
element.bind('keypress', (event) => {
const keyCode = event.which || event.keyCode; // get the keyCode pressed from the event.
const keyCodeChar = String.fromCharCode(keyCode); // determine the char from the keyCode.
// keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field.
if (!keyCodeChar.match(new RegExp(attrs.allowPattern, 'i'))) {
event.preventDefault();
return false;
}
return true;
});
};
},
};
}
})();下面是我正在运行的单元测试,它失败了,
ngDescribe({
name: 'allow-pattern',
modules: ['app.utilities'],
inject: ['$compile'],
tests (deps) {
let scope;
let element;
function compileDirective () {
scope = deps.$rootScope.$new();
element = deps.$compile('<input allow-pattern="[0-9]">')(scope);
scope.$digest();
return element;
}
function triggerhandler (eventCode) {
element.triggerHandler({ type: 'keypress', which: eventCode });
}
it.only('sets value if it matches the pattern', () => {
compileDirective();
triggerhandler(57); // keycode for 5
scope.$digest();
console.log(element.val());
});
},
});现在,每当我运行这个测试时,我希望element.val()的值应该是5,但它返回的却是空字符串。我不能理解哪里出了问题。谁能指出问题所在?
我正在使用因果报应和幻影。
提前谢谢。
https://stackoverflow.com/questions/44547593
复制相似问题