访问全局变量JavaScript单元测试 [英] Access for global variables JavaScript unit testing

查看:54
本文介绍了访问全局变量JavaScript单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是新的JavaScript单元测试,并且正在使用Mocha.js和Chai.js

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

我想做的只是简单地弄清楚如何在单独的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

这是main.js文件(要测试的代码),只有我要测试的变量.

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

//main.js
var foo = 9;

这是我的测试文件

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);
    });
});

再次,我是JavaScript单元测试的新手.任何帮助将不胜感激.我得到的错误是 foo未定义,它告诉我它无法访问该变量,那么如何访问它呢?预先感谢您的帮助.

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.

推荐答案

var foo = 9; 不声明全局变量,而是声明局部变量.在Node.js中,在模块的最外层范围内声明的局部变量对于该模块是局部的.

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.

如果要测试在另一个文件中声明的局部变量的值,最好的选择可能是将该文件的内容读入字符串(也许使用 fs.readFileSync ),然后然后是 eval()字符串,该字符串应在当前作用域中定义变量.

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

这篇关于访问全局变量JavaScript单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆