Search code examples
javascriptangularjstestingprotractorend-to-end

How to check the presence of a DOM element in protractor?


Just want to click the log off link if it exists. No action if that link is not present.

Here is the code:

browser.get(browser.baseUrl + 'login');

var lnkLogOff = element(by.linkText('Log off'));
if (lnkLogOff.isPresent()) lnkLogOff.click();

It appears nothing is wrong. But I got a NoSuchElementError when the link is not on page.

What is the correct way to check the presence of an element in protractor?


Solution

  • You can use isElementPresent():

    var locator = by.linkText('Log off');
    browser.isElementPresent(locator).then(function (present) {
        if (present) {
            element(locator).click();
        }
    });