isDisplayed() and NoSuchElementError exception

By definition isDisplayed() is a method, that return Boolean value - True if the element is visible in the UI and False if it is not (please check Difference between Selenium visibility methods for more details).

But there is one exception - the response:

Copy
NoSuchElementError: No element found using locator

Why do you see this error?

By default, isDisplayed() will return False in case where the element exist in the DOM, but it has setting the CSS "visibility" property to "hidden", or the "display" property to "none", either for the element itself or one if it's ancestors.

In case your element is not found at all, and you are checking this by using findElement(), then the response you will see is NoSuchElementError, which is passed from findElement to isDisplayed().

How to fix it

Simply wrap isDisplayed() in your own method and handle the unresolved/rejected promise with a call similar to one of the following two scenarios:

  1. You want to do something when the element is displayed. When it is not, you want to throw a specific exception, with a detailed message. The exception will stop the rest of the code in the test method from executing.

    Copy
    try {
    element.isDisplayed();
    doSomething();
    }
    catch (NoSuchElementException e) {
    throw new RuntimeException("This is where you put the message");
    }
  2. You expect that your element should not be displayed. Then it will throw an exception and stop your execution, since there is no point to proceed.

    The execution of the code will proceed only if your element is displayed.

    Copy
    try {
    element.isDisplayed();
    fail("Element should not have been displayed but it was!");
    }
    catch (NoSuchElementException e) {}
Note:

Please note that If the element is cached, StaleElementReferenceException is thrown instead.