Define test variables in QUnit setup
Asked Answered
W

1

8

I realized that the QUnit.module provides setup and teardown callbacks surrounding each tests.

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

As seen in setup, I want to declare a variable to use across the following QUnit.tests. However, since the variable only has function scope, the two tests fail, saying usedAcrossTests is undefined.

I could remove the var declaration, but then that would pollute the global scope. Especially if I will have multiple modules, I'd rather not be declaring test-specific variables as global.

Is there a way to specify, in setup a variable to be used in the tests within the module, without polluting the global scope?

Wendolynwendt answered 20/6, 2014 at 5:24 Comment(0)
G
17

I just realized that it is more simpler than my previous answer. Just add all properties that you want to access in all other test of modules in current object.

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

And then in each test where you wish to use this.

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

Hope this helps

Gula answered 20/6, 2014 at 5:54 Comment(1)
This advice is still helpful in 2019 working with QUnit 2.x (see qunitjs.com/upgrade-guide-2.x). We need to be careful, however, in a complex set of tests, with nested modules. The 'this' context in the nested module is not the 'this' context of the parent module, so you need to create a variable in the parent module like 'self' (or 'that' or whatever) and assign the parent 'this' context to it. The nested module then has access to the parent context via the variable 'self'.Hush

© 2022 - 2024 — McMap. All rights reserved.