如何使用量angular器来检查一个元素是否可见?

我试图testing一个元素是否可见使用量angular器。 以下是元素的样子:

<i class="icon-spinner icon-spin ng-hide" ng-show="saving"></i> 

在Chrome控制台中,我可以使用这个jQueryselect器来testing元素是否可见:

 $('[ng-show=saving].icon-spin') [ <i class=​"icon-spinner icon-spin ng-hide" ng-show=​"saving">​</i>​ ] > $('[ng-show=saving].icon-spin:visible') [] 

但是,当我尝试在量angular器中执行相同的操作时,运行时出现此错误:

 InvalidElementStateError: invalid element state: Failed to execute 'querySelectorAll' on 'Document': '[ng-show=saving].icon-spin:visible' is not a valid selector. 

为什么这是无效的? 如何使用量angular器检查可视性?

这应该做到这一点:

 expect($('[ng-show=saving].icon-spin').isDisplayed()).toBeTruthy(); 

记住量angular器的$不是jQuery和:visible不是可用的CSSselect器+伪select器的一部分

更多信息在https://stackoverflow.com/a/13388700/511069

使用量angular器检查元素的可见性的正确方法是调用isDisplayed方法。 你应该小心,虽然isDisplayed不返回一个布尔值,而是提供评估的可见性的promise 。 我见过很多错误地使用这种方法的代码示例,因此不会评估它的实际可见性。

获取元素可见性的示例:

 element(by.className('your-class-name')).isDisplayed().then(function (isVisible) { if (isVisible) { // element is visible } else { // element is not visible } }); 

然而,如果你只是检查元素的可见性(而不是得到它),那么你不需要这个,因为Jasmine expect()的量angular器补丁,所以它总是等待promise被解决。 请参阅github.com/angular/jasminewd

所以你可以做:

 expect(element(by.className('your-class-name')).isDisplayed()).toBeTruthy(); 

既然你使用的是AngularJS来控制这个元素的可见性,你也可以像下面这样检查它的类的属性:

 var spinner = element.by.css('i.icon-spin'); expect(spinner.getAttribute('class')).not.toMatch('ng-hide'); // expect element to be visible 

我有一个类似的问题,因为我只想要在页面对象中可见的返回元素。 我发现我可以使用CSS :not 。 在这个问题的情况下,这应该是你…

 expect($('i.icon-spinner:not(.ng-hide)')).isDisplayed().toBeTruthy(); 

在一个页面对象的上下文中,你可以只用这种方式获得那些可见的元素。 例如。 给定一个页面上有多个项目,其中只有一些是可见的,你可以使用:

 this.visibileIcons = $$('i.icon:not(.ng-hide)'); 

这将返回你所有可见的i.icon

如果DOM中有多个元素具有相同的类名称。 但是只有一个元素是可见的。

 element.all(by.css('.text-input-input')).filter(function(ele){ return ele.isDisplayed(); }).then(function(filteredElement){ filteredElement[0].click(); }); 

在这个例子中,filter使用isDisplayed()方法获取元素的集合并返回一个可见的元素。

这个答案足够健壮,可以处理不在页面上的元素,因此,如果select器未能find元素,将会失败(不抛出exception)。

 const nameSelector = '[data-automation="name-input"]'; const nameInputIsDisplayed = () => { return $$(nameSelector).count() .then(count => count !== 0) } it('should be displayed', () => { nameInputIsDisplayed().then(isDisplayed => { expect(isDisplayed).toBeTruthy() }) }) 
Interesting Posts