0

I need to run some eval code inside of a mocha test in nodejs, but I keep running into an issue. I cannot do any var declarations inside of a test. So, if I have something like this:

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

});

The test 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)

But if I change it to:

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

    });

The test passes. Any ideas on how to fix this problem? EDIT: I need to do variable declarations inside the string.

Sanchit Anand
  • 195
  • 2
  • 11
  • 2
    What is the purpose of this test ? Why can't you do a variable declaration inside of a test ? – NayoR Apr 18 '18 at 19:20
  • This is an obviously simplified version of my real tests. I'm testing a babel plugin. – Sanchit Anand Apr 18 '18 at 19:21
  • 1
    Hm, it's not evident to answer with so few elements. Is it possible to put directly the ouput into `expect`, like `expect(eval("testVar = 1;")).eq(1);` ? Can't you declare the variable `testVar` outside of the test ? In any case use `eval` function is not recommanded [for many reasons](https://stackoverflow.com/a/86580/9640261) – NayoR Apr 18 '18 at 19:28
  • Thank you for the feedback, but I need to do variable declarations in a string. – Sanchit Anand Apr 18 '18 at 19:33
  • 1
    This is the kind of useful information for helping answering to your problem.. If you must use eval (is it the case ?): `expect(eval("var testVar; testVar = 1; testVar")).eq(1);` – NayoR Apr 18 '18 at 19:39
  • Yeah, that seems to do the trick, thanks. I will keep this question open incase someone gives me a better answer. – Sanchit Anand Apr 18 '18 at 19:44

1 Answers1

1

If you can't do any variable declaration and you must use eval, you can directly test eval's output:

expect(eval("var testVar; testVar = 1; testVar")).eq(1);
NayoR
  • 702
  • 6
  • 13