Selenium: How to correctly test whether an element is displayed (or not)

Published by

on

One of the most frequent kind of interactions with the web page when testing with Selenium is checking whether a particular element is present. More specifically, whether it is visible when looking at the page and does not have a “hidden” attribute. The isDisplayed() method is used for such checks, but in many cases it is not used properly. Some tests appear to be unreliable when it comes to checking that the element is displayed, and that is mostly because of the way this method is used. Below are some example of how TO and NOT TO use the method for checking the presence / absence of an element on the page.

When to check that the element is displayed

One thing worth mentioning is that the presence of an element is evaluated in a lazy way, when an interaction with it is attempted, by default (when the element is defined in a Page Object class, by using the @FindBy annotations).

Think about the scenario you want to test. Why are you interested in the presence of an element? Do you need to interact with it in anyway (click on it or get one of its’ properties)? If the answer is no (you just need to make sure of the presence of the element), than it’s fine to use the isDisplayed method.
However if the answer is yes, well think again. Let’s analyze the logic a bit: you need to check whether an element is there, actually you need to make sure it is there (the test will fail in case it isn’t) and do something with it after you know it’s there. You are performing two steps in this case: check the presence of an element, then use it. For this scenario, you are performing one too many steps. When trying to interact with an element, if it is not present, the interaction will result in an error/exception anyhow, so the first step (checking for the presence) is useless. For this case you should remove the first step, and just interact with the element directly.
So in the example when you want to click on an element, no need to check whether it is displayed first. Just click on it (and you will basically find out at this step whether it was displayed or not, since its’ absence will not make the click possible and an exception will be thrown).

How to test that the element is displayed/not displayed

As mentioned, Selenium provides testers this wonderful method named isDisplayed(). If used properly, this will solve your issue of knowing whether an element is on the page or not.

So what happens when you call isDisplayed on an element?
1. If the element really is visible, the method will return true.
2. If the element is not visible, it will throw an exception. It will NOT return false. This is how this method is implemented within the Selenium library. Therefore, the following pieces of code are not correct:

if (!element.isDisplayed()) {
doSomething();
}

When the element is not displayed, the returned value by isDisplayed is not a boolean, so it cannot be negated. In this example, the doSomething() method, or any other subsequent code, will not be executed if the element is not there.

if (element.isDisplayed()) {
doSomething(); 
}
else {
doSomethingElse();
}

This last piece of code will only work if the element is displayed. Otherwise, during the evaluation of the isDisplayed code, the exception will be thrown and the ‘else’ part will not be executed (and neither will be any subsequent code in this test method).

Let’s consider some scenarios and the proper way of testing for the presence of elements:

  1. You only want to do something when the element is displayed. When it is not, you don’t necessarily care what kind of exception is thrown. In this case, the NoSuchElementException will be thrown, and no further code in the test method will be executed. You don’t even need to put an ‘if’ clause here. If the element will be encountered, the isDisplayed expression will return true, and it will continue the execution of the code with the instruction it has below.
  2. element.isDisplayed()
    doSomething();
    
  3. 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.
  4. try {
    element.isDisplayed();
    doSomething();
    }
    catch (NoSuchElementException e) {
    throw new RuntimeException("This is where you put the message");
    }

    3. Your element should not be displayed. In case it is, throw an exception. This will stop the rest of the code from running (no point in continuing if a condition is not met). If the element is there, continue executing the rest of the code.

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

10 responses to “Selenium: How to correctly test whether an element is displayed (or not)”

  1. Mike Clark Avatar

    Corina, as I was going through some of my manual tests, I wanted to find a smarter way in automating the ones that check for elements presence on a page. This article was absolutely what I was looking for, and loved the way you explained it, each step of the way. I’m early on in my journey in becoming an automation engineer, so I really appreciate people like yourself, in sharing and explaining information for us newbies!

    Like

    1. iamalittletester Avatar
      iamalittletester

      Thank you for the feedback. I am always glad to hear that my posts help people with automation.

      Liked by 1 person

  2. Rob Avatar
    Rob

    Hi! What if I would like to verify error msg on the page? Let’s say, some service is not available and error text appears on the page. If(text.size() > 0) {dosomething} is working fine, if error appears. But I got unable to find element error when it doesn’t. So I’m looking for a solution, do the test check the error on the page, but if no errors, just continue the test. Thanks in advance!

    Like

    1. iamalittletester Avatar
      iamalittletester

      Just so i understand correctly: – if no error appears, you want the test to just run normally; – but if an error occurs you want to check for what the error is? And if the error occurs what do you expect from the test? To fail or pass?

      Like

  3. Bobby Washington Avatar
    Bobby Washington

    This is an amazing post. I’ve been fighting with the problem all day. Your explanation and example is a complete and total life saver! Thank you so much!!!

    Like

  4. Sagar Avatar
    Sagar

    The last point says – 3)Your element should not be displayed. In case it is, throw an exception. This will stop the rest of the code from running (no point in continuing if a condition is not met). If the element is there, continue executing the rest of the code.

    My case is in the other way. My element should not be displayed. In case it is, generate one more element and run through a loop. Once the element is not displayed, continue executing the rest of the code.

    Like

  5. nlazouzi Avatar
    nlazouzi

    i’d like to know why selenium is not catching the exception and returning false….
    i’m sure they have a good reason

    Like

  6. Mark Walters Avatar
    Mark Walters

    I’m a bit surprised in the third paragraph above that you have overlooked one very common reason for checking for the presence of an element before using it, which is that the element may not have loaded yet. I come across this all the time (FYI I use additional tools, but that only means I can use different keywords to achieve the same), and I don’t want the test to fail simply because the page is still loading.

    Like

  7. Vladimir Belorusets Avatar
    Vladimir Belorusets

    You are saying that isDisplayed() does not return the boolean value. However, in the latest Javadoc for WebElement https://www.selenium.dev/selenium/docs/api/java/index.html the method returns boolean, as shown below
    boolean isDisplayed()
    Is this element displayed or not? This method avoids the problem of having to parse an element’s “style” attribute.
    Returns: Whether or not the element is displayed

    Like

    1. iamalittletester Avatar
      iamalittletester

      If the element is displayed, you will get a boolean as result of this method. If the element is not present in HTML/DOM, an Exception will be thrown, namely NoSuchElementException.

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.