[英]Unit testing AngularJS Directive with isolated scope - how to get bindings to output?
我真的需要有關使用Isolated Scope測試AngularJS指令的建議和指導。
說我有以下指令(有效):
angular.module('myApp')
.directive('pageNav', function() {
return {
restrict: 'A',
scope: {
title: '@'
},
transclude: true,
templateUrl: 'pageNav.html',
link: function(scope, element, attrs) {
if (attrs.pageNav == 'translucent') {
element.find('nav').addClass('newClass');
}
}
};
})
;
這是模板URL代碼:
<nav class="pageNav">
<div class="content">
<h1 ng-if="title">{{ title }}</h1>
<div class="contentRight" ng-transclude></div>
</div>
</nav>
現在我有以下測試
describe('Page Nav Directive', function() {
var $scope,
element;
beforeEach(module('myApp'));
beforeEach(module('pageNav.html'));
beforeEach(inject(function($compile, $rootScope) {
$scope = $rootScope;
$scope.title = "hey hey, my my";
element = angular.element('<div page-nav></div>');
// element = angular.element('<div page-nav title="hey hey, my my"></div>');
$compile(element)($scope);
$scope.$digest();
}));
it('should render the directive', function() {
// this test will fail if I un-comment the element above
expect(element.find('div').eq(1).attr('class')).toBe('contentRight');
});
it('should render a title', function() {
// this test will pass if I un-comment the element above
expect(element.find('h1').eq(0).text()).toBe('hey hey, my my');
});
})
;
現在,即使我設置了$scope.title
(由於某種原因未渲染綁定{{ title }}
我也不明白為什么第二個測試對第一個元素失敗了)。 現在,如果我將$scope.title
放在元素上作為屬性,則第二個測試將在渲染工作時通過,但是第一個測試失敗? 我什至將第一個測試更改為
expect(element.scope().find('div').eq(1).attr('class')).toBe('contentRight');
當使用時,我將$scope.title
放在元素上作為屬性,但這也失敗了。
我發現很少或沒有很好的文檔來測試帶有隔離范圍的AngularJS指令,並且不知所措。 對於我遇到的問題的任何指導,信息或解釋,將不勝感激。
問題1:設置$scope.title
(由於某種原因未顯示綁定{{ title }}
)
當然,因為您使用的是title: '@'
,所以@
表示您要綁定靜態字符串。
問題2:
您正在使用templateUrl
,瀏覽器必須啟動ajax請求以加載模板,這意味着該指令的模板尚未在當前函數中加載 , 必須等待ajax請求完成=>結果不可預測。
如此DEMO所示,如果我立即在同一函數中檢查已編譯的html,則會發現它沒有被編譯。 為了向您顯示templateUrl是正確的並稍后加載,我使用console.log
和對象引用添加了另一個DEMO來證明它。
如果我使用內聯template
(如本DEMO中所示) ,則替換模板(但不進行編譯)。
問題三:
Angular js編譯功能未在當前功能中完成,您可能需要使用$ timeout將其計划為下一個周期。 DEMO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.