【发布时间】:2014-01-07 13:19:04
【问题描述】:
我真的需要有关使用独立作用域测试 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');
}
}
};
})
;
这是模板网址代码:
<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 指令的良好文档,我正在努力解决问题。对我遇到的问题的任何指导、信息或解释将不胜感激。
【问题讨论】:
-
您能否为此创建一个 jsffidle。它将帮助我们更快地帮助您
-
这是一个原始的小提琴...jsfiddle.net/itakesmack/ecfpz
-
你检查过小提琴的工作原理吗?
-
我刚刚添加了上面的代码,因为我使用的是业力/茉莉花,我希望有人能解释一下渲染和范围的问题,而不是修改代码。
-
设置
$scope.title(由于某种原因绑定{{ title }}没有呈现)。当然,因为您使用的是title: '@',所以@意味着您使用静态字符串进行绑定。
标签: javascript unit-testing angularjs angularjs-directive karma-runner