DRYing up protractor clicks tests using a For-Loops

空扰寡人 提交于 2019-12-06 06:02:21

the above answers and approaches all seem to take a 'synchronous' approach, so I'd like to offer the solution I found for the same issue which uses the standard asynchronous protractor approach.

In this example, the footer links are text links such as 'ABOUT', CONTACT', etc. - and these map to URLs such as '/about' and '/contact', etc.

Edit: ptor is defined earlier from protractor.getInstance();

it('should have a working set of footer links to internal pages', function() {
  // element.all( -your selectors- )
  // .then() is passed an ARRAY of element finders 
  element.all(by.css('.footer .nav .links')).then(function(elems) {

    // for each element .getText() returns a promise
    var txts = elems.map(function(elem) {
      return elem.getText().then(function(txt) {
        if(txt != ''){
          return txt;
        }
      });
    });

    // txts is now an ARRAY of promises
    // When they are ALL fulfilled the loop below is run
    protractor.promise.all(txts).then(function(links) {
      for (var i=0; i<links.length; i++) {
        // reset browser back to page of interest
        // the home page in this case
        browser.get('/');

        // get a fresh instance of the element and click it
        // attempts to click pre-created element list
        // will result in 'stale' elements references as pages
        // are being navigated
        element.all(by.css('.footer .nav .links')).get(i).click();

        // expectation of navigation
        expect(ptor.getCurrentUrl()).toContain(links[i].toLowerCase());
      }
    });

  });

});
Matthew Harwood

DUPLICATE: ANSWER HERE

You need to wrap the it block in an IIFE to force synchrony

for(var i=0; i < testParams.length; i++) {

    (function(testSpec) {
        it('write your test here', function() {
            //test code here
        }
    })(testParams[i]);

};

Your main problem is:

return elm.getText;

getText is a method that returns a promise. So what you'll need is more like

return elm.getText().then(function(text){
    return text;
});

When you call a method like getText or getInnerHtml, it only returns a promise. Provided you aren't using expect, If you want the promise resolved in order to get the value, you need to chain then to return the value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!