gpt4 book ai didi

javascript - QUnit.test 在 for 循环中运行

转载 作者:行者123 更新时间:2023-11-30 12:04:00 25 4
gpt4 key购买 nike

我正在尝试为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com