javascript 量角器,使用 isDisplayed() 我得到 NoSuchElementError: No element found using locator

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30099903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:40:18  来源:igfitidea点击:

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

javascriptangularjsjasmineprotractorangularjs-e2e

提问by Mikel

In protractor 2.0, I am checking in a expect()if one element is displayed. I expect a false, but the weird thing is that I get following error:

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

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

NoSuchElementError:使用定位器找不到元素:By.id("userForm")

My code is:

我的代码是:

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();
    });
});

I understand that I get that error because element is not longer on the page (is what I want to confirm), but shouldn't I get a false and not a error?

我知道我收到该错误是因为页面上不再显示元素(这是我要确认的内容),但是我不应该得到错误而不是错误吗?

回答by alecxe

isDisplayed()would check if an element is visible or not, but you need to check whether an element is present in DOM or not, use isElementPresent()or isPresent():

isDisplayed()将检查元素是否可见,但您需要检查元素是否存在于 DOM 中,使用isElementPresent()or isPresent()

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

See also:

也可以看看:

回答by Vasiliy Vanchuk

This error is part of WebDriver behavior. For such cases you should better use isPresentor isElementPresent

此错误是 WebDriver 行为的一部分。对于这种情况,您最好使用 isPresentisElementPresent

回答by Sergiy Podgorniy

If element visible do A if not visible do B, disregard exception if element not found:

如果元素可见做 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
});