我正在尝试为 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 中找到了答案.正如这篇非常好的帖子中所说:
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.
关于javascript - QUnit.test 在 for 循环中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35792987/