测试时如何访问指令中的attr-Angularjs

How do I access the attr in a directive when testing - Angularjs

本文关键字:指令 attr-Angularjs 访问 何访问 测试      更新时间:2024-06-04

我有一个指令正在尝试测试。这是指令:

App.directive('resize', function($animate) {
  return function(scope, element, attrs) {
    scope.$watch(attrs.resize, function(newVal) {
      if(newVal) {
        $animate.addClass(element, 'span8');
      }
    });
  };
});

这是我的测试:

describe('resize', function() {
  var element, scope;
  beforeEach(inject(function($compile, $rootScope) {
    var directive = angular.element('<div class="span12" resize="isHidden"></div>');
    element = $compile(directive)($rootScope);
    $rootScope.$digest();
    scope = $rootScope;
  }));
  it('should change to a span8 after resize', function() {
    expect($(element).hasClass('span12')).toBeTruthy();
    expect($(element).hasClass('span8')).toBeFalsy();
    element.scope.newVal = 'changed';
    scope.$apply();
    expect($(element).hasClass('span8')).toBeTruthy();
  });
});

我正在尝试访问我的attrs变量,更改它,$apply,并查看class是否按预期进行了更改。我无法更改attrs。实际上,我甚至找不到访问它的方法。我如何在测试中访问attrs

element是一个jqLite对象,或者是一个普通的jQuery对象(如果在AngularJS之前加载jQuery)。只需使用.attr()方法:

it('should do something on attr change', function(){
    element.attr('resize', 'newValue');
    $scope.$apply();
});

不需要将元素包装在一个新的jQuery对象中:$(element)就可以使用.hasClass(value)方法