我有一个自定义指令,它根据另一个服务的值显示/隐藏一个元素。我尝试创建一个测试来查看该指令是否执行了应该执行的操作。一开始我再次测试了“:visible”选择器,但它总是返回 false,即使我知道该元素确实在显示。
it('Should show element if logged', function () {
element = angular.element('<p hc-auth>Some Text</p>');
AuthService.Logged = true;
scope = $rootScope.$new();
scope.$apply(function () {
$compile(element)(scope);
});
expect(element.is(":visible")).toBeTruthy();
});
经过一些调试,我意识到在测试执行期间,即使显示设置为阻塞,元素的宽度和高度也为 0,因此“:visible”选择器始终返回 false。我将其改为检查显示选择器,现在它可以正确测试元素,但这似乎太依赖于如何显示元素的实现。
it('Should show element if logged', function () {
element = angular.element('<p hc-auth>Some Text</p>');
AuthService.Logged = true;
scope = $rootScope.$new();
scope.$apply(function () {
$compile(element)(scope);
});
expect(element.css('display')).toBe('block');
});
解决这种情况的最佳方法是什么?
最佳答案
你的问题让我想知道 Angular 是如何测试 ngHide
和 ngShow
的,这是他们规范文件中的一个片段:
it('should show if the expression is a function with a no arguments', function() {
element = jqLite('<div ng-show="exp"></div>');
element = $compile(element)($scope);
$scope.exp = function() {};
$scope.$digest();
expect(element).toBeShown();
});
看起来很整洁。起初我以为他们一定是在使用 jquery-jasmine它确实公开了一个 toBeHidden
匹配器(尽管事实证明不是 toBeShown
),事实上他们写了自己的 custom matcher用于确定可见性:
// [jtrussell] Custom Jasmine Matcher
toBeShown: function() {
this.message = valueFn(
"Expected element " + (this.isNot ? "" : "not ") + "to have 'ng-hide' class");
return !isNgElementHidden(this.actual);
}
// [jtrussell] ...
// [jtrussell] The helper from elsewhere in same file
function isNgElementHidden(element) {
// we need to check element.getAttribute for SVG nodes
var hidden = true;
forEach(angular.element(element), function(element) {
if ((' ' + (element.getAttribute('class') || '') + ' ').indexOf(' ng-hide ') === -1) {
hidden = false;
}
});
return hidden;
}
所以我猜他们有点作弊...检查是否存在 .ng-hide
类以确定可见性。但我想他们曾经站在你的立场上,并认为这是最好的路线,因为 angular 已经支持这个类名。
由于我们已经在使用 Angular,或许您可以考虑使用 .ng-hide
类来设置可见性并编写类似的帮助程序。
编辑:
作为旁注,我会说添加/删除 .ng-hide
以设置可见性的好处是可以免费获得模块用户已经为其设置的任何 ngAnimations那个类。
关于javascript - 测试自定义 Angular Directive(指令)是否显示/隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831906/