Search code examples
javascriptnode.jsqunit

node-qunit doesn't include my source files in scope


I've installed node-qunit (stable) from npm, but can't seem to get any tests working. My source files don't seem to be included in scope.

./source/myscript.js:

var myObj = {
    a : true
}

./test/tests.js:

test("that a is true", function () {
     ok(myObj.a);
});

./test/runner.js:

var runner = require('qunit');
runner.run({
    code : './source/myscript.js',
    tests : './test/tests.js'
});

./Makefile:

test :
<tab>node ./test/testrunner.js

.PHONY: install test

If I run make test, I get a 'ReferenceError: myObj is not defined' error. The source file does run, because it can throw errors. It just doesn't seem to be included in the global scope as it should. It doesn't work if I do it from the command line, as per the instructions in the node-qunit readme. Anyone have any idea how to get this working?


Solution

  • You're not exporting anything. Behind the scenes, node-qunit is using require to load the specified modules. To expose variables when a module is required, you have to add them to the exports object (or assign your own object to the exports variable)

    (There's also a syntax error - ; in the object literal)

    This works for me:

    ./source/myscript.js:

    exports.myObj = {
      a: true
    }
    

    ./test/tests.js:

    QUnit.module('tests')
    
    test("that a is true", function () {
      ok(myObj.a)
    })
    

    ./test/runner.js:

    var runner = require('qunit')
    
    runner.run({
      code : './source/myscript.js'
    , tests : './test/tests.js'
    })