Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define test variables in QUnit setup

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?

like image 795
geoff Avatar asked Jun 20 '14 05:06

geoff


People also ask

How do you write a test case on Qunit?

Create a Test Case Make a call to the QUnit. test function, with two arguments. Name − The name of the test to display the test results. Function − Function testing code, having one or more assertions.

What are hooks in Qunit?

You can use hooks to prepare fixtures, or run other setup and teardown logic. Hooks can run around individual tests, or around a whole module. before : Run a callback before the first test. beforeEach : Run a callback before each test.

What is jQuery testing?

jQuery QUnit is a test framework created by the same impressive folks who bring you jQuery. It is lightweight, easy to understand, and easy to use. It has a number of simple methods that allow you to test your code.

How do I install Qunit?

Local Installation Go to the https://code.jquery.com/qunit/ to download the latest version available. Place the downloaded qunit-git. js and qunit-git. css file in a directory of your website, e.g. /jquery.


1 Answers

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

like image 67
khagesh Avatar answered Oct 01 '22 23:10

khagesh