范围。$ watch在范围之后不会被触发。$ digest in karma unit test

时间:2015-06-05 16:22:14

标签: javascript angularjs unit-testing karma-jasmine

我想测试这个指令:

.directive('mwIcon', function () {
  return {
    restrict: 'A',
    scope: {
      mwIcon: '@',
      tooltip: '@',
      placement: '@',
      style: '@'
    },
    template: '<i ng-class="iconClasses" style="{{style}}" mw-tooltip="{{tooltip}}" placement="{{placement}}"></i>',
    link: function (scope, el) {

      el.addClass('mw-icon');
      //set icon classes
      scope.$watch('mwIcon', function (newVal) {
        if (newVal) {
          var isFontAwesome = angular.isArray(scope.mwIcon.match(/^fa-/)),
            isRlnIcon = angular.isArray(scope.mwIcon.match(/rln-icon/));
          if (isFontAwesome) {
            scope.iconClasses = 'fa ' + scope.mwIcon;
          } else if (isRlnIcon) {
            scope.iconClasses = 'rln-icon ' + scope.mwIcon;
          } else {
            scope.iconClasses = 'glyphicon glyphicon-' + scope.mwIcon;
          }
        }
      });
    }
  };
})

特别是当我改变scope.mwIcon时会发生什么。它也应该更改<i>元素的类,因为scope.mwIcon有一个观察者,对吗?这是我的考验:

it('should change the class according to the new icon', function () {
  var icon = '<span mw-icon="search"></span>';
  var el = $compile(icon)(scope);
  scope.$digest();

  expect(el.children().hasClass("glyphicon")).toBe(true);
  expect(el.children().hasClass("glyphicon-search")).toBe(true);

  scope.mwIcon = "fa-star";
  scope.$digest();

  expect(el.children().hasClass("fa")).toBe(true);
  expect(el.children().hasClass("fa-star")).toBe(true);
});

尽管我用scope.mwIcon触发了scope.$digest的更改,但最后两个断言返回false。任何想法为什么我的<i>元素仍然有“glyphicon glyphicon-search”类而不是“fa fa-star”?

2 个答案:

答案 0 :(得分:0)

您将mwIcon绑定到属性字符串(带@),因此随后设置scope.mwIcon,不会触发$ watch。您可以将其更改为双向绑定(mwIcon:&#39; =&#39;,)或尝试使用attr。$ observe,将attrs添加为链接功能的第三个arg,尽管我没有&# 39;尝试了最后一种方法。

答案 1 :(得分:0)

问题是该指令使用的是隔离范围。在隔离范围上设置新mwIcon时,测试可以正常工作。

it('should change the class according to the new icon', function () {
  var icon = '<span mw-icon="search"></span>';
  var el = $compile(icon)(scope);
  var isolatedScope = el.isolateScope();

  scope.$digest();

  expect(el.children().hasClass("glyphicon")).toBe(true);
  expect(el.children().hasClass("glyphicon-search")).toBe(true);

  isolatedScope.mwIcon = "fa-star";
  scope.$digest();

  expect(el.children().hasClass("fa")).toBe(true);
  expect(el.children().hasClass("fa-star")).toBe(true);
});