vendredi 5 juin 2015

scope.$watch does not get triggered after scope.$digest in karma unit test

I want to test this directive:

.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;
          }
        }
      });
    }
  };
})

Specifically what happens when I change scope.mwIcon. It should change the class of the <i> element as well, since scope.mwIcon has a watcher, right? This is my test:

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);
});

The bottom two assertions return false, even though I triggered a change of scope.mwIcon with scope.$digest. Any ideas why my <i> element still has classes "glyphicon glyphicon-search" and not "fa fa-star"?

Aucun commentaire:

Enregistrer un commentaire