isDisplayed() and NoSuchElementError exception
By definition, isDisplayed()
is a method that returns a 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:
NoSuchElementError: No element found using locator
Why do you see this error?
By default, isDisplayed()
returns False in cases where the element exists in the DOM, but its CSS "visibility
" property is set to "hidden
", or the "display
" property is set to "none
", either for the element itself or one of its ancestors.
In case your element is not found at all, and you are checking this by using findElement()
, then you get the response 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:
-
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 stops the rest of the code in the test method from executing.
Copytry {
element.isDisplayed();
doSomething();
}
catch (NoSuchElementException e) {
throw new RuntimeException("This is where you put the message");
} -
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.
Copytry {
element.isDisplayed();
fail("Element should not have been displayed but it was!");
}
catch (NoSuchElementException e) {}
If the element is cached, StaleElementReferenceException
is thrown instead.