check if element is present in protractor

时间秒杀一切 提交于 2020-01-16 18:54:28

问题


I have an angular application where user can get a different login screen(non-angular) based on her/his browser cache. I am writing end to end test cases using protractor and I want to put a condition something like this

if(this element is present)
{
click it
}
else check if this element is pressent
{
click it
}

This is what I have tried.

  browser.driver.findElements(by.id('element1')).then(function(result) {
      if (result) {
        browser.driver.findElement(by.id('element1')).click();
      }
      else {
        browser.driver.findElement(by.id('element2')).sendKeys("username");
      }
    }
  );

My issue is that if the element in the 'if condition' is not present then I am getting an error ' Failed: no such element: Unable to locate element:'. I don't want my test cases to fail because it's possible that the element is not present and then it should go to else block. I have seen so many questions on stackoverflow but nothing helped me. I would really appreciate any help here.

Update: please note that this is a non-angular screen and I can only use browser.driver.______ apis.


回答1:


You were very much on the right track. Because findElements returns an array, you just needed to change what you had if (result) to if (result.length>0). With FindElements, finding nothing is not an error.



来源:https://stackoverflow.com/questions/50806848/check-if-element-is-present-in-protractor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!