我有一个自定义指令,该指令基于另一个服务的值显示/隐藏一个元素。我尝试创建一个测试,以查看该指令是否执行了应该执行的操作。一开始,我再次测试了“: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');
});
解决这种情况的最佳方法是什么?
您的问题让我想知道如何进行角度测试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
事实并非如此),实际上,他们编写了自己的自定义匹配器来确定可见性:
// [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,也许您可以考虑使用.ng-hide
该类来设置可见性并编写类似的帮助器。
编辑:
附带说明一下,我要说的是,添加/删除.ng-hide
以设置可见性将具有免费获取模块用户已为该类准备的任何ngAnimations的好处。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句