nodejs 运行 在测试用例内部进行评估

nodejs run eval inside of testcase

我需要 运行 在 nodejs 的 mocha 测试中使用一些 eval 代码,但我一直 运行 遇到问题。我不能在测试中做任何 var 声明。所以,如果我有这样的事情:

it("7.Variable Assignment", function(done){
    eval("var testVar = 1;");
    expect(testVar).eql(1);
    done();

});

测试returns:

   7.Variable Assignment:
 ReferenceError: testVar is not defined
  at eval (eval at <anonymous> (test/index.js:102:16), <anonymous>:1:1)
  at Context.<anonymous> (test/index.js:102:16)

但如果我将其更改为:

it("7.Variable Assignment", function(done){
        var testVar;
        eval("testVar = 1;");
        expect(testVar).eql(1);
        done();

    });

测试通过。关于如何解决此问题的任何想法? 编辑:我需要在字符串中做变量声明。

如果不能做任何变量声明,必须使用eval,可以直接测试eval的输出:

expect(eval("var testVar; testVar = 1; testVar")).eq(1);