Skip to content Skip to sidebar Skip to footer

Access For Global Variables Javascript Unit Testing

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.

Solution 1:

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).

Solution 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.

Post a Comment for "Access For Global Variables Javascript Unit Testing"