7

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

3 Answers 3

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();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.