最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if an element exists in Protractor - Stack Overflow

programmeradmin5浏览0评论

I have been trying to use the code snippet below to check if the element I'm looking for exists, however all I get is "Failed: No element found using locator: By(css selector, .icon-cancel)". What I want the program to do is to execute b()

element(by.css('.icon-cancel')).isDisplayed().then(function(result) {
    if ( result ) {
        a();
    } else {
        b();
    }
});

I have been trying to use the code snippet below to check if the element I'm looking for exists, however all I get is "Failed: No element found using locator: By(css selector, .icon-cancel)". What I want the program to do is to execute b()

element(by.css('.icon-cancel')).isDisplayed().then(function(result) {
    if ( result ) {
        a();
    } else {
        b();
    }
});
Share Improve this question asked Jun 9, 2016 at 14:48 user3400351user3400351 2331 gold badge5 silver badges18 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

isDisplayed() would fail if an element does not actually exist in the DOM tree. You need the isPresent() method instead:

$('.icon-cancel').isPresent().then(function(result) {
    if ( result ) {
        a();
    } else {
        b();
    }
});

One possibility is, if the element is loaded dynamically, the element may not have been loaded by the time your test is running. So you can wait for a few seconds for the element to be available.

var EC = protractor.ExpectedConditions;
var yourElement = element(by.css('.icon-cancel'));
browser.wait(EC.presenceOf(yourElement), 5000);

By using async/await you can now easily to this without the promise chain:

it('should something something', async () => {
    const element = element(by.css('.icon-cancel'));
    if(await element.isPresent()) {
        // Element is found
    } else {
        // Element is not found
    }
});
发布评论

评论列表(0)

  1. 暂无评论