In protractor, browser.isElementPresent vs element.isPresent vs element.isElementPresent

alecxe picture alecxe · Oct 8, 2015 · Viewed 18.7k times · Source

In protractor, there are, basically, 3 ways to check if an element is present:

var elm = element(by.id("myid"));

browser.isElementPresent(elm);
elm.isPresent();
elm.isElementPresent();

Are these options equivalent and interchangeable, and which one should be generally preferred?

Answer

Girish Sortur picture Girish Sortur · Oct 14, 2015

All function in a similar way with subtle differences. Here are few differences that i found -

elm.isPresent() -

  1. Is an extension of ElementFinder and so waits for Angular to settle on page before executing any action.
  2. It works when elm is an element(locator) or ElementFinder and not ElementArrayFinder. If multiple elements are returned using the locator specified then first element is checked if it isEnabled() in the DOM. Doesn't take any parameter as input.
  3. Works best with Angular pages and Angular elements.
  4. First preference to use whenever there is a need to find if an element is present.

elm.isElementPresent(subLoc) - (When there is a sub locator to elm)

  1. Is an extension of ElementFinder and so waits for Angular to settle on page before executing any action.
  2. Used to check the presence of elements that are sub elements of a parent. It takes a sub locator to the parent elm as a parameter. (only difference between this and the elm.isPresent())
  3. Works best with Angular pages and Angular elements.
  4. First preference to use whenever there is a need to check if a sub element of a parent is present.

browser.isElementPresent(element || Locator) -

  1. Is an implementation of webdriver and so doesn't wait for angular to settle.
  2. Takes a locator or an element as a parameter and uses the first result if multiple elements are located using the same locator.
  3. Best used with Non-Angular pages.
  4. First preference to use when testing on non-angular pages.

All of the above checks for the presence of an element in DOM and return a boolean result. Though angular and non-angular features doesn't affect the usage of these methods, but there's an added advantage when the method waits for angular to settle by default and helps avoid errors in case of angular like element not found or state element reference exceptions, etc...