koral koral - 2 months ago 11
TypeScript Question

e2e tests with protractor - how to return selected menu item from function inside page model

I have a menu

<ul class="menu">
with items
<li>
. In e2e tests I use page model.

In a spec I want to call page model function which:


  • check that only one menu item has class
    selected

  • return its index



My code

describe('Main screen and global navigation', () => {
class MainPage {
load() {
browser.get('');
}

getMainMenuActiveItemIndex(): number {
let list = element.all(by.css('ul.menu li'));
// iterate somehow
return 0;
}

navigate(itemClass: string) {
let menuItem = element(by.css('ul.menu li.' + itemClass));
menuItem.click();
}
}

let p = new MainPage();

beforeEach(function () {
p.load();
});
it('should navigate to subpages', () => {
expect(p.getMainMenuActiveItemIndex()).toBe(0);
p.navigate('invoices');
expect(p.getMainMenuActiveItemIndex()).toBe(1);
});
})


I know that
element...
return promise. But I don't know how to return result of this promise from function i.e. how to resolve promise before returning function value.

Or maybe should I return promise from function instead of number?

Answer

This is how you need to do it,

 getMainMenuActiveItemIndex() {
     return element.all(by.css('ul.menu li')).getAttribute('class').then((classArray) => {
          for(let i = 0; i < classArray.length; i++){
            if (classArray[i].indexOf('selected') > -1){
                 return i;
              }
          }
          return -1; //if none of the li element have class `selected` then return -1
       })
    }