edu*_*glz 5 html javascript css jquery angularjs
我有一个自定义指令,根据另一个服务的值显示/隐藏元素.我尝试创建一个测试,看看该指令是否做了应该做的事情.在开始时,我再次测试了":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();
});
Run Code Online (Sandbox Code Playgroud)
经过一些调试后,我意识到在测试执行期间,即使显示设置为阻塞,元素的宽度和高度也为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');
});
Run Code Online (Sandbox Code Playgroud)
这种情况的最佳方法是什么?
你的问题让我想知道如何角测试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();
});
Run Code Online (Sandbox Code Playgroud)
看起来很整洁.起初我认为他们必须使用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;
}
Run Code Online (Sandbox Code Playgroud)
所以我猜他们有点作弊......检查一个.ng-hide类的存在以确定可见性.但我想他们曾经在你的鞋子里,并认为这是最好的路线,因为角度已经支持这个类名.
既然我们已经在使用angular,你可以考虑使用.ng-hide类来设置可见性并编写类似的帮助器.
编辑:
作为旁注,我会说添加/删除.ng-hide设置可见性将有利于免费获得模块用户已经为该类设置的任何ngAnimations.