Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: Check for the presence of element

Tags:

selenium

In real-time automation, do we check for the presence of every element (in test) before performing some action on them?

Wherever there is a findElement statement, there is a chance of NoSuchElementException. Should we check for the presence of the element every time?

Does every findElement statement need to be surrounded by a try-catch block?

like image 523
Mehavarnan Murugan Avatar asked Oct 14 '25 14:10

Mehavarnan Murugan


1 Answers

There are two cases to account for:

  1. Is the element present; meaning does it exist in the DOM.
  2. Is the element visible; meaning it is in DOM and does not have a hidden or equivalent flag.

For the first case, I use the following helper method:

this.waitForElement = function(locator) {
    browser.wait(function() {
      return browser.isElementPresent(locator);
    }, testData.Timeout.TWO_MINUTES);
};

This will wait for an arbitrary amount of time for the element matching the provided locator to become present (It exists in the DOM).

For the second case, I use this helper method:

this.waitForElementIsVisible = function(el){
    let EC = protractor.ExpectedConditions;
    browser.wait(EC.visibilityOf(el), testData.Timeout.TWO_MINUTES, "Element did not become visible after 2 minutes");
};

This takes a WebElement as the single parameter and waits until the element becomes visible (it exists in the DOM and is not hidden via a CSS style or something).

As a bonus, I also found this helper method to be useful for testing error states in a form:

this.waitForElementIsClickable = function(el){
    let EC = protractor.ExpectedConditions;
    browser.wait(EC.elementToBeClickable(el), testData.Timeout.TWO_MINUTES, "Element did not become clickable after 2 minutes");
};

Takes a WebElement as the first parameter and waits until that WebElement can be clicked.

Note, I am using Protractor, and reference Protractor in these snippets. So unless you are using Protractor as well, it's likely these will not work 100% through a straight copy+paste. It should be easy enough to tweak them to suite your setup, though.

like image 117
lTyl Avatar answered Oct 18 '25 06:10

lTyl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!