23

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:

NoSuchElementError: No element found using locator: 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?

Mikel
  • 5,902
  • 5
  • 34
  • 49

4 Answers4

36

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():

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

See also:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 3
    You're a "protractor angel!" I've learned a lot from your answers here! thank you! @alecxe – Idan E Jul 10 '15 at 15:52
  • 1
    @IdanE and I've learned a lot from your questions! Thank you! – alecxe Jul 10 '15 at 18:27
  • If i do it in condition. it is not working. ex. `if(browser.isElementPresent(element(by.id('userForm')))` – ji-ruh Jan 21 '17 at 17:46
  • @ji-ruh `browser.isElementPresent(element(by.id('userForm'))` returns a promise which is always "truthy". You should explicitly resolve the promise to check the actual presence value. – alecxe Jan 22 '17 at 03:02
2

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

Vasiliy vvscode Vanchuk
  • 7,007
  • 2
  • 21
  • 44
2

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

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

.isDisplayed() assumes the element is present (exists in the DOM)

so if you do

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

but the element is not present, then instead of graceful failed expectation, $('[ng-show=saving]').isDisplayed() will throw an error causing the rest of it block not executed

Solution

If you assume, the element you're checking may not be present for any reason on the page, then go with a safe way below

/**
*  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())
}

and use

expect(await isDisplayed( $('[ng-show=saving]') )).toBe(true);
Sergey Pleshakov
  • 7,964
  • 2
  • 17
  • 40