1

I am new to protractor for automating angularJs apps. I am trying to select one element from a list of elements. I am trying to do error handling, but nothing works as I expected because of the promises.

In the following code, if I pass an invalid categoryName it never prints the error instead it goes to the verification part(expect) and fail.

Please help me understand this and how can I resolve this issue. I tried using callback but not luck. I also tried try catch and still no luck. Appreciate any help here. Thanks

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;
        });
    })
};
kvm006
  • 4,554
  • 2
  • 18
  • 22

2 Answers2

1

Use filter() and check how many elements matched:

var filteredCategories = this.elements.filter(function (category) {
    return category.getText().then(function (text) {
        return text === categoryName;
    });
});  
expect(filteredCategories.count()).toEqual(1);
filteredCategories.first().click();
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • In my use case, I am not selecting the element from a dropdown or selection box. I have a column of elements with different category names. Does filter() work in that scenario? – kvm006 Feb 21 '16 at 07:17
  • @VarunMukka sure, give it a try. – alecxe Feb 21 '16 at 12:02
1

If you want to log Invalid cases, you can do like this.

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");
   }
}
kvm006
  • 4,554
  • 2
  • 18
  • 22