Continue if element is not visible in protractor

2019-07-17 05:39发布

问题:

I want to check if an element is visible and if it's not, I want my test to continue with something else.

The problem is that if element is not visible, nothing seems to be working... I've already tried isDisplayed(), isPresent(), invisibilityOf()... but test fails if element is not visible. Eg.

 element(myElement).isDisplayed().then(function(result) {
      if (result) {
      //do something
      }
    else {
     //do something else
     }
    }

This works just fine if myElement is present. But if not, test fails with error: No element found using locator: By.cssSelector(myCss). So somehow it doesn't resolve the promise returned by isDisplayed(), so it never goes to else section. What can I do to keep my test running if element is not displayed?

回答1:

You can chain promises to resolve this issue. This function will return true only if element both is present and is displayed.

var isApproachable = function(element) {
  return element.isPresent().then(function(present) {
    return present
      ? element.isDisplayed()
      : false;
  });
}

isApproachable(myElement).then(function(approachable) {
  if (approachable) ...
});


回答2:

To clarify, isDisplayed requires an element actually be rendered in the browser. isPresent means the element is listed in the dom (and/or visible).

isDisplayed will fail if the element doesn't exist, so you can't use it to test for existence. You need to use isPresent.

You can test this thusly:

describe('isPresent', function() {
    it('should not fail if element does not exist', function() {
        browser.get('http://google.com');
        // this will fail if you use isDisplayed
        $('#doesNotExist').isPresent().then(function(inDom) {
            if(inDom) {
                console.log('I EXIST!!!!1!');
            } else {
                console.log('NOT HERE...');
            }
        });
    });
});


回答3:

You could trap the error in an empty function. This is however dangerous if a different error occurs besides the "No element found using locator: By.cssSelector(myCss)" error you get, such as "Stale element".

element(myElement).isDisplayed().then(function(result) {
  if (result) {
    //do something
  }
  else {
    //do something else
  }
}.thenCatch(function(err) {};


标签: protractor