【问题标题】:How to handle element not found exception in Protractor如何处理量角器中未找到元素的异常
【发布时间】:2017-01-31 06:18:37
【问题描述】:

就像 Selenium webdriver 为 Java 提供了各种异常处理一样,有什么方法可以使用 Protractor 来实现。

如果我们想处理 element not found 异常,那么使用 Protractor 最好的方法是什么?

【问题讨论】:

  • 嗯...您能否编辑您的问题以添加代码并提供更多详细信息?

标签: javascript selenium selenium-webdriver protractor


【解决方案1】:

回答这个问题is now in Protractor's FAQ

如何捕捉 ElementNotFound 等错误?

当命令无法完成时,WebDriver 会抛出错误 - 例如无法单击被另一个元素遮挡的元素。如果您需要重试这些操作,请尝试使用webdriverjs-retry。如果您只想捕获错误,请这样做

根据您的问题改编:

elm.isPresent().then(function(present) {
  /* no webdriver js errors here */}
  if (present) {
    /* element exists */
  } else {
    /* element doesn't exist */
  }
, function(err) {
  /* error handling here, i.e. element doesn't if got ElementNotFound
     but, eventually and less likely, other issues will fall in here too like
     NoSuchWindowsError or ElementStaleError etc...
  */
});

【讨论】:

  • 对我来说非常及时的帖子。这很有帮助。
【解决方案2】:

感谢@Leo Gallucci 对 OP 问题的改编:

我今天遇到了这个问题,希望能找到一个像这样看起来干净的解决方案:

/* Function to check for three possible DOM elements; return the element which exists, and get the text contents. */
this.getMySelector =  function(){
 if (element(by.css('.mySelector')).isPresent()){
   return element(by.css('.mySelector'));
 }
 else if (element(by.css('.mySelector2')).isPresent()){
   return element(by.css('.mySelector2'));
 }
 else{
  return element(by.css('.mySelector3'));
 }
}

然而,它总是点击第一个if() 而从不检查其他条件。结果我需要为我的场景链接承诺:

this.getMySelector =  function(){
    
  element(by.css('.mySelector')).isPresent().then(function (pres) {
    if (pres){
      defer.fulfill(  by.css('.mySelector')).getText() );
    }
    else{
       element(by.css('.mySelector2')).isPresent().then(function (pres) {
         if (pres){
            defer.fulfill(..);
         }
       }
    }
  }
}

// From calling test-spec.js file
getMySelector.then(function(text)){
   console.log('Now I got the text ==> ' + text);         
}
                                                        
                                                       

【讨论】:

    【解决方案3】:

    试一试,Catch 在 Protractor 中具有以下语法。下面的代码将首先通过 Id 'IdTextBoxCode' 找到一个元素。然后代码输入代码'codeTextBox.sendKeys(code);'在 TRY 块中。如果代码抛出异常(在这种情况下,如果没有找到 Id 为“IdTextBoxCode”的元素),那么它将转到 catch 块和错误处理函数。

    browser.driver.findElement(by.id(browser.params.loginPage.IdTextBoxCode)).then(function(codeTextBox)
        {
            try 
            {
                console.log("Entering Code: "+code);
                codeTextBox.sendKeys(code);
            }
            catch(err) {
                console.log('In catch block');
            }
       }, function(err) {
            console.info('Code Text Box not displayed on page. Proceeding with default Code');
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2013-10-23
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多