我想测试这个指令:
.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;
}
}
});
}
};
})
特别是当我改变scope.mwIcon
时会发生什么。它也应该更改<i>
元素的类,因为scope.mwIcon
有一个观察者,对吗?这是我的考验:
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);
});
尽管我用scope.mwIcon
触发了scope.$digest
的更改,但最后两个断言返回false。任何想法为什么我的<i>
元素仍然有“glyphicon glyphicon-search”类而不是“fa fa-star”?
答案 0 :(得分:0)
您将mwIcon绑定到属性字符串(带@),因此随后设置scope.mwIcon,不会触发$ watch。您可以将其更改为双向绑定(mwIcon:&#39; =&#39;,)或尝试使用attr。$ observe,将attrs添加为链接功能的第三个arg,尽管我没有&# 39;尝试了最后一种方法。
答案 1 :(得分:0)
问题是该指令使用的是隔离范围。在隔离范围上设置新mwIcon
时,测试可以正常工作。
it('should change the class according to the new icon', function () {
var icon = '<span mw-icon="search"></span>';
var el = $compile(icon)(scope);
var isolatedScope = el.isolateScope();
scope.$digest();
expect(el.children().hasClass("glyphicon")).toBe(true);
expect(el.children().hasClass("glyphicon-search")).toBe(true);
isolatedScope.mwIcon = "fa-star";
scope.$digest();
expect(el.children().hasClass("fa")).toBe(true);
expect(el.children().hasClass("fa-star")).toBe(true);
});