QUnit.test 运行 在 for 循环中

QUnit.test running in a for loop

我正在尝试为 QUnit 测试做一些代码重构。我使用 json 数组 TestCaseSource 来存储测试用例的输入和预期输出,并像这样编码,

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]);
    });
}

使用这段代码,我只能得到第一个和最后一个测试用例运行。 QUnit 省略了中间的所有情况。如果我删除了 for 循环,并硬编码 QUnit.test 就像

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

那时一切都很好。为什么 for 循环不起作用?

我在 Asynchronous Process inside a javascript for loop 中找到了答案。正如它在这个非常好的 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.