I am facing a challenge in creating a loop to navigate through multiple pages and generate slightly different tests for each page. The asynchronous nature of the task is causing confusion, making it difficult to come up with a solution. When attempting to use a normal loop, the page always ends up being set to the last one in the array. I have experimented with closures in various ways, but unfortunately, nothing has worked so far. Despite finding valuable insights from this question, I am still struggling to make things function as intended.
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 results in displaying Page3
three times because the loop executes almost instantly. Attempting to implement a closure leads to an obscure error and crashes before any execution takes place.
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]();
}