【问题标题】:Define test variables in QUnit setup在 QUnit 设置中定义测试变量
【发布时间】:2014-06-20 05:24:21
【问题描述】:

我意识到QUnit.module 提供围绕每个测试的设置和拆卸回调。

QUnit.module("unrelated test", {
    setup: function() {
        var usedAcrossTests = "hello";
    }
});
QUnit.test("some test", function(assert) {
    assert.deepEqual(usedAcrossTests, "hello", "uh oh");
});
QUnit.test("another test", function(assert) {
    assert.deepEqual(usedAcrossTests.length, 5, "uh oh");
});

setup 中所见,我想声明一个变量以在以下QUnit.tests 中使用。但是,由于变量只有函数作用域,所以两个测试都失败了,说usedAcrossTests is undefined

我可以删除var 声明,但这会污染全局范围。特别是如果我将有多个模块,我宁愿不将特定于测试的变量声明为全局变量。

有没有办法在setup 中指定要在模块内的测试中使用的变量,而不会污染全局范围?

【问题讨论】:

    标签: javascript scope qunit


    【解决方案1】:

    我刚刚意识到它比我之前的答案更简单。 只需在当前对象的所有其他模块测试中添加您要访问的所有属性。

    QUnit.module("unrelated test", {
        setup: function() {
            this.usedAcrossTests = "hello"; // add it to current context 'this'
        }
    });
    

    然后在您希望使用它的每个测试中。

    QUnit.test("some test", function(assert) {
        assert.deepEqual(this.usedAcrossTests, "hello", "uh oh");
    });
    

    希望对你有帮助

    【讨论】:

    • 这个建议在 2019 年使用 QUnit 2.x 时仍然很有帮助(请参阅 qunitjs.com/upgrade-guide-2.x)。但是,在使用嵌套模块的一组复杂测试中,我们需要小心。嵌套模块中的“this”上下文不是父模块的“this”上下文,因此您需要在父模块中创建一个变量,如“self”(或“that”或其他)并分配父“this” ' 的上下文。然后嵌套模块可以通过变量“self”访问父上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多