Nightwatch Execute Command Within For Loop Runs Out Of Order
I'm pretty new to unit testing, but I've been trying to create a script with Nightwatch that goes through the body content of a page, clicks every link and reports back whether it'
Solution 1:
This has nothing to do with Nightwatch, but with Javascript.
When you have a loop and you call a function within that loop, the variable used in such function is saved by reference. In other words, the variable doesn't change for any of the functions.
It's easier if we go through a simple example:
var myFuncs = [];
for (var i = 0; i < 3; i += 1) {
myFuncs.push(function () {
console.log('i is', i);
});
}
myFuncs[0](); // i is 3
myFuncs[1](); // i is 3
myFuncs[2](); // i is 3
This is because i
is saved as a reference in the function. So when i
increments at the next iteration, the referenced doesn't change but the value does.
This could be easily fixed by moving the function outside of the loop:
functionlog (i) {
returnfunction () {
console.log(i);
}
}
var myFuncs = [];
for (var i = 0; i < 3; i += 1) {
myFuncs.push(log(i));
}
myFuncs[0](); // i is 0
myFuncs[1](); // i is 1
myFuncs[2](); // i is 2
In case you want to explore the concept a little bit more, you can have a look at this similar SO answer (which has a very similar example - ironically).
Post a Comment for "Nightwatch Execute Command Within For Loop Runs Out Of Order"