首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试属性的angularjs指令

测试属性的angularjs指令
EN

Stack Overflow用户
提问于 2017-06-14 22:27:39
回答 0查看 56关注 0票数 0

我有以下指令,它工作得很好,现在我需要对它进行单元测试,

代码语言:javascript
复制
(() => {
  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;
          });
        };
      },
    };
  }
})();

下面是我正在运行的单元测试,它失败了,

代码语言:javascript
复制
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,但它返回的却是空字符串。我不能理解哪里出了问题。谁能指出问题所在?

我正在使用因果报应和幻影。

提前谢谢。

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44547593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档