3

Hello I am new JavaScript unit testing and I'm using Mocha.js and Chai.js

What I want to do is simply figure out how to check the value of a global variable in a seperate js file. Here is my code

Here is the main.js file (code to be tested) Just has the variable I want to test against.

//main.js
var foo = 9;

Here is my test file

var assert = require("assert")
var expect = require('chai').expect
var fs = require("fs")
var vm = require("vm")

function include(path){
    var code = fs.readFileSync(path,'utf-8');
    vm.runInThisContext(code,path);
}

describe('Global', function(){
    include('lib/main.js');
    it('Should check if value is matching', function(){
        expect(foo).to.equal(9);
    });
});

Again, I'm new to unit testing in JavaScript. Any help will be greatly appreciated. The error I get back is foo is not defined which tells me that it can't access the variable, so how can I access it? Thank you in advance for the help.

0

2 Answers 2

2

var foo = 9; does not declare a global variable, it declares a local variable. In Node.js, a local variable declared in the outermost scope of a module will be local to that module.

If you want to test the value of a local variable declared in another file, your best bet is probably to read the contents of that file into a string (using fs.readFileSync, perhaps) and then eval() the string, which should define the variable in the current scope.

That will only work if the local variable is declared in the file's outermost scope. If it's a local variable inside a function, for example, you're out of luck (unless you want to do some gnarly string parsing, which would stretch the bounds of sanity).

Sign up to request clarification or add additional context in comments.

Comments

2

Your global object is usually window

a global var foo = "test"; is the same as window.foo = "test"; or window['foo'] = "test";

Window is not defined when mocha is run in node, but this blog post uses "this" combined with a self-invoking function to get the same result.

3 Comments

Yeah window doesn't run in node. Sorry for not clarifying. Using this just returns undefined for the argument.
ok, you're right it's not as clear as it should have been. I'll edit it accordingly. Thanks, @Louis!
In Node.js the global object is global.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.