【问题标题】:Testing angularjs directive for attribute测试属性的 angularjs 指令
【发布时间】:2017-06-14 14:27:38
【问题描述】:

我有以下指令可以正常工作,现在我需要对其进行单元测试,

(() => {
  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,但它会返回空字符串。我无法理解出了什么问题。谁能指出问题?

我正在使用 karma 和 phantomjs。

提前致谢。

【问题讨论】:

    标签: javascript angularjs unit-testing angularjs-directive chai


    【解决方案1】:

    好吧,我认为我正在测试错误的测试用例。我只想测试我的正则表达式是否匹配,那么应该调用 event.preventDefault()。我做了什么,它完美地通过了。我使用 sinon.spy 来监视阻止默认值,它起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多