Protractor, with isDisplayed() I get NoSuchElementError: No element found using locator

Protractor, with isDisplayed() I get NoSuchElementError: No element found using locator

在量角器 2.0 中,如果显示一个元素,我将检查 expect()。我期待一个错误,但奇怪的是我得到以下错误:

NoSuchElementError: No element found using locator: By.id("userForm")

我的代码是:

describe('closeModal', function() {
    it('should close the alert that appears after registration.', function(){
        element(by.id('closeAlertModalButton')).click();
        expect(element(by.id('userForm')).isDisplayed()).toBeFalsy();
    });
});

我知道我收到那个错误是因为元素不再出现在页面上(这是我想确认的),但我不应该得到错误而不是错误吗?

此错误是 WebDriver 行为的一部分。对于这种情况,你应该更好地使用 isPresent or isElementPresent

isDisplayed() 会检查一个元素是否可见,但是你需要检查一个元素是否存在于 DOM 中,使用 isElementPresent() or isPresent():

expect(browser.isElementPresent(element(by.id('userForm')))).toBe(false);
expect(element(by.id('userForm')).isPresent()).toBe(false);

另请参阅:

  • How do I test if an img tag exists?

如果元素可见则执行 A 如果不可见则执行 B,如果未找到元素则忽略异常:

element.isDisplayed().then(function(visible){
    if (visible) {
        // do A when element visible
    }else{
        // do B when element not visible 
    }
}, function () {
    //suppress exception if element is not found on page
});

.isDisplayed() 假定元素存在(存在于 DOM)

所以如果你这样做

expect($('[ng-show=saving]').isDisplayed()).toBe(true);

但是该元素不存在,那么 $('[ng-show=saving]').isDisplayed() 将抛出一个错误,导致 it 块的其余部分未执行

而不是优雅的失败期望

解决方案

如果您认为您正在检查的元素可能由于任何原因不在页面上,那么请按照下面的安全方式进行操作

/**
*  element is Present and is Displayed
*  @param    {ElementFinder}      $element       Locator of element
*  @return   {boolean}
*/
let isDisplayed = function ($element) {
  return (await $element.isPresent()) && (await $element.isDisplayed())
}

并使用

expect(await isDisplayed( $('[ng-show=saving]') )).toBe(true);