简体   繁体   中英

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 ie how to resolve promise before returning function value.

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

Just return the promise. Protractor's expect() will resolve it automatically. You dont have to give then()

Feel free to ask for clarifications

Edit 1: i guess you got the answer from @sudharsa. But i suggest you to use filter function instead of then function in getMainMenuActiveItemIndex()

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
       })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM