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

标签 javascript qunit

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

相关文章:

javascript - 检查checkbox是否勾选并传递数据

javascript - 函数修改不反射(reflect)在输出中

javascript - 有没有一种好方法可以在多个地方设置 assert.expect(n) ?

javascript - 模拟 Controller 用于 qunit 测试。

javascript - Nest Js TypeORM repository.update 方法不更改对象的多个字段

javascript - 使用内部有 GIF 的 CSS 移动 div。 GIF 在移动时暂停

javascript - 如果 css ("top") 等于或大于 -70(负值)

javascript - 异步加载 qUnit

json - Ember-auth QUnit 测试每运行一次就会失败

javascript - React 路由器不工作需要模块