1

I was trying to do some code refactoring for QUnit tests. I used a json array TestCaseSource to store test case's input and expected output, and coded like this,

var data = TestCaseSource.data;

for (var i in data) {
    console.log(data[i]);
    QUnit.test(data[i].TestCaseName, function () {
        DoProcess(data[i].TestCaseName, "", data[i]);
    });
}

With this code, I could only have the first and last test case run. All the cases in the middle were omitted by QUnit. If I removed the for loop, and hard coded QUnit.test like,

    QUnit.test('TestCaseName1', function () {
        DoProcess('TestCaseName1', "", TestCaseSource.data[0]);
    });
    QUnit.test('TestCaseName2', function () {
        DoProcess('TestCaseName2', "", TestCaseSource.data[1]);
    });
    ...

Everything was fine then. Why the for loop was not working?

John Mccandles
  • 1,181
  • 2
  • 16
  • 24

1 Answers1

3

I found my answer in Asynchronous Process inside a javascript for loop . As it says in this very nice post:

You have to freeze the value of i by passing it into a function somewhere so it's value exists uniquely for each iteration of the loop in a function closure. Otherwise, all asynch callbacks will just see the value of i at the end of the loop which is the value it has when they execute their callbacks (sometime later when the loop has finished), not each their own value.

Community
  • 1
  • 1
John Mccandles
  • 1,181
  • 2
  • 16
  • 24