2016-02-19 34 views
1

我是量角器的新角色,用于自动化angularJs应用程序。我试图从元素列表中选择一个元素。我正在尝试进行错误处理,但由于承诺,我无法按预期工作。角度量角器中的错误处理

在下面的代码中,如果我传递一个无效的categoryName,它永远不会打印错误,而是转到验证部分(期望)并失败。

请帮我理解这一点,我该如何解决这个问题。我尝试使用回调,但不是运气。我也尝试尝试赶上,仍然没有运气。感谢这里的任何帮助。由于

this.elements = element.all(by.css('.xyz')); 
this.selectCategory = function (categoryName) { 
    this.elements.each(function (category) { 
     category.getText().then(function (text) { 
      if (text === categoryName) { 
       log.info("Selecting Category"); 
       category.click(); 
      } 
     }, function (err) { 
      log.error('error finding category ' + err); 
      throw err; 
     }); 
    }) 
}; 

回答

1

使用filter()和检查有多少元素匹配:

var filteredCategories = this.elements.filter(function (category) { 
    return category.getText().then(function (text) { 
     return text === categoryName; 
    }); 
}); 
expect(filteredCategories.count()).toEqual(1); 
filteredCategories.first().click(); 
+0

在我的用例中,我没有从下拉列表或选择框中选择元素。我有一列具有不同类别名称的元素。 filter()在那种情况下工作吗? – kumarvarun

+0

@VarunMukka当然,试试看吧。 – alecxe

+0

谢谢,那工作:) – kumarvarun

1

如果你想记录无效的情况下,你可以这样做。

this.selectCategory = function (categoryName) { 

    var filteredCategories = this.categoryElements.filter(function (category) { 
     return category.getText().then(function (text) { 
      return text === categoryName; 
     }) 
    }) 

    filteredCategories.count().then(logInvalidCategory) 

    expect(filteredCategories.count()).toEqual(1); 
    filteredCategories.first().click(); 
} 

function logInvalidCategory(count) { 

    if(count === 0) { 
     log.info("Invalid Category"); 
    } 
}