2013-12-09 40 views
0

我有一條指令,我正在測試。這裏是指令:如何在測試中訪問指令中的attr?Angularjs

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

回答

1

element是一個jqLite object,或一個普通的jQuery對象(如果您在AngularJS之前加載jQuery)。只需使用.attr()方法:

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

這是沒有必要來包裝元件在一個新的jQuery對象:$(element)使用.hasClass(value)方法

+0

我可以設置一個屬性與'element.attr(」但是當我嘗試訪問'element.attrs()'存在'attrs'時,我得到了'TypeError:無法讀取'undefined'屬性'nodeType'。這是爲什麼? – jhamm

+0

我必須特別要求這個屬性,比如'element.attr('resize')' – jhamm