Access for global variables JavaScript unit testing

风格不统一 提交于 2019-12-12 17:14:59

问题


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.


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




回答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.



来源:https://stackoverflow.com/questions/28510355/access-for-global-variables-javascript-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!