1

I'm trying to create a loop that navigates through several pages, and creates tests that are slightly different for each page. The fact that it's asynchronous is throwing me off, and I haven't been able to figure out a way to do it. Trying to use just a normal loop results in the page always being set to the very last page in the array. I've tried using a closure in a few different ways, but haven't had any luck. I think that's the proper route to go though. I've looked at this question, and it gave me some good ideas, but I still haven't been able to get things to work.

var bs = new BasicSteps();

describe("Some description", function() {
    var pages = ['/page1', '/page2', '/page3'];

    var i = 0;
    beforeEach(function() {
        bs.navigate(pages[i]);
        browser.sleep(2000);
        i++;
    });

    for(page in pages) {
        // Code for the spec
        it('Some spec', function() {
            // Some code for the tests
            if(page == 1) {
                console.log("page1");
            }
            else if(page == 2) {
                console.log("Page2");
            } 
            else if(page == 3) {
                console.log("Page3");
            }
        });
    }
});

This prints out Page3 three times, since the loop executes pretty much immediately. I've tried using a closure, but this causes some obscure error and just crashes before anything runs.

var funcs = [];

function createfunc(page) {
    return function() {
        // Code for the spec
    });
}

for(var page = 0; page < pages.length; page++) {
    funcs[page] = createfunc(page);
}

for(var j = 0; j < funcs.length; j++) {
    funcs[j]();
}
Community
  • 1
  • 1
123
  • 8,733
  • 14
  • 57
  • 99

1 Answers1

0

You can use a closure to work around Protractors asynchronous promises to create tests in a loop if you have a set of pages that need to have the same test applied to them.

To write your test loop, you would do something like the following:

// Array of objects with name and URL of each page
var pages = [{'name': 'page1', 'url': 'someurl.com/page1'},
             {'name': 'page2', 'url': 'someurl.com/page2'}];

describe("Some description", function(){
  function specBlock(curPage) {
    describe(curPage.name, function(){
      it('Some test', function () {
        // Test goes here
      });
    });
  };

  createSpecBlock = function(specBlock) {
    return specBlock;
  }

  var funcCall = createSpecBlock(specBlock);

  pages.forEach(function(curPage){
    funcCall(curPage);
  });
});
123
  • 8,733
  • 14
  • 57
  • 99