En transportador, navegador.isElementPresent vs element.isPresent vs element.isElementPresent


En protractor, hay, básicamente, 3 maneras de comprobar si un elemento está presente:

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

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

¿Son estas opciones equivalentes e intercambiables, y cuál debería preferirse en general?

Author: djangofan, 2015-10-08

3 answers

Todos funcionan de manera similar con diferencias sutiles. Aquí hay algunas diferencias que encontré -

elm.isPresent() -

  1. Es una extensión de ElementFinder y por lo tanto espera que Angular se establezca en page antes de ejecutar cualquier acción.
  2. funciona cuando elm es element(locator) o ElementFinder y no ElementArrayFinder. Si se devuelven varios elementos utilizando el locator especificado, el primer elemento se comprueba si isEnabled() en el DOM. No toma ningún parámetro como entrada.
  3. Funciona mejor con páginas Angulares y elementos Angulares.
  4. Primera preferencia para usar cuando hay una necesidad de encontrar si un elemento está presente.

elm.isElementPresent(subLoc) - (Cuando hay un sub localizador a elm)

  1. Es una extensión de ElementFinder y espera a que Angular se establezca en page antes de ejecutar cualquier acción.
  2. Se utiliza para comprobar la presencia de elementos que son subelementos de un padre. Toma un sub locator al padre elm como un parámetro. (única diferencia entre esto y el elm.isPresent())
  3. Funciona mejor con páginas Angulares y elementos Angulares.
  4. Primera preferencia para usar siempre que sea necesario verificar si un subelemento de un padre está presente.

browser.isElementPresent(element || Locator) -

  1. Es una implementación de webdriver y por lo tanto no espera a que angular se asiente.
  2. Toma un locator o un element como parámetro y usa el primer resultado si varios elementos se encuentran usando el mismo localizador.
  3. Se usa mejor con páginas no angulares.
  4. Primera preferencia para usar cuando se prueba en páginas no angulares.

Todas las comprobaciones anteriores para la presencia de un elemento en DOM y devuelve un resultado boolean. Aunque las características angulares y no angulares no afectan el uso de estos métodos, hay una ventaja adicional cuando el método espera a que angular se establezca de forma predeterminada y ayuda a evitar errores en caso de que angular like element not found o state element reference excepciones, etc...

 32
Author: Girish Sortur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-14 19:50:03

No puedo hablar sobre cuál es el preferido, pero pude encontrar el código fuente y examinarlo.

Según los documentos, elm.isPresent() y elm.isElementPresent() son equivalentes. Espero que eso ayude.

Documentos de la API de transportador

Hay un enlace a View code justo a la derecha del título.

Navegador.isElementPresent (elm);

Https://angular.github.io/protractor/#/api?view=webdriver.WebElement.prototype.isElementPresent

/**
 * Schedules a command to test if there is at least one descendant of this
 * element that matches the given search criteria.
 *
 * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The
 *     locator strategy to use when searching for the element.
 * @return {!webdriver.promise.Promise.<boolean>} A promise that will be
 *     resolved with whether an element could be located on the page.
 */
webdriver.WebElement.prototype.isElementPresent = function(locator) {
  return this.findElements(locator).then(function(result) {
    return !!result.length;
  });
};

Elm.isPresent ();

Https://angular.github.io/protractor/#/api?view=ElementFinder.prototype.isPresent

/**
 * Determine whether the element is present on the page.
 *
 * @view
 * <span>{{person.name}}</span>
 *
 * @example
 * // Element exists.
 * expect(element(by.binding('person.name')).isPresent()).toBe(true);
 *
 * // Element not present.
 * expect(element(by.binding('notPresent')).isPresent()).toBe(false);
 *
 * @return {ElementFinder} which resolves to whether
 *     the element is present on the page.
 */
ElementFinder.prototype.isPresent = function() {
  return this.parentElementArrayFinder.getWebElements().then(function(arr) {
    if (arr.length === 0) {
      return false;
    }
    return arr[0].isEnabled().then(function() {
      return true; // is present, whether it is enabled or not
    }, function(err) {
      if (err.code == webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE) {
        return false;
      } else {
        throw err;
      }
    });
  }, function(err) {
    if (err.code == webdriver.error.ErrorCode.NO_SUCH_ELEMENT) {
      return false;
    } else {
      throw err;
    }
  });
};

Elm.isElementPresent ();

Https://angular.github.io/protractor/#/api?view=ElementFinder.prototype.isElementPresent

/**
 * Same as ElementFinder.isPresent(), except this checks whether the element
 * identified by the subLocator is present, rather than the current element 
 * finder. i.e. `element(by.css('#abc')).element(by.css('#def')).isPresent()` is
 * identical to `element(by.css('#abc')).isElementPresent(by.css('#def'))`.
 *
 * @see ElementFinder.isPresent
 *
 * @param {webdriver.Locator} subLocator Locator for element to look for.
 * @return {ElementFinder} which resolves to whether
 *     the subelement is present on the page.
 */
ElementFinder.prototype.isElementPresent = function(subLocator) {
  if (!subLocator) {
    throw new Error('SubLocator is not supplied as a parameter to ' + 
      '`isElementPresent(subLocator)`. You are probably looking for the ' + 
      'function `isPresent()`.');
  }
  return this.element(subLocator).isPresent();
};
 4
Author: JeffC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-08 17:12:06

Puede comprobar si el elemento está presente o no mediante la función isPresent.

Entonces, tu código sería algo así como:

var myElement = element(by.css('.elementClass'));
expect(myElement.isPresent()).toBeFalsy();

Aquí está la documentación del transportador para la función isPresent.

 -3
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-14 06:14:23