Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocha Global Scoping Issues

I'm having a big problem with my mocha tests around a global object I'm using. I'm able to produce the following MRE which doesn't give the exact same error, but exemplifies the problematic (buggy?) behavior. Any insight would be much appreciated.

I have the following main.js file in /lib:

exports.exec = function(){
  console.log(test);
}

Then the following in /test/test.js:

var should = require('should');
var main = require('../lib/main');

global.test = {something: 1};

describe('normal test', function(){
  beforeEach(function(){
    global.test = {another: 2};
  }),

  afterEach(function(){
    delete global.test;
  });

  it ('might work with global', function(){
    main.exec();
  })
});

Finally, this is test/test2.js:

var should = require('should');
var main = require('../lib/main');

global.test = {third: 3};

describe('some test', function(){
  it ('messes up global', function(){
    main.exec();
  })
});

I expect that the first test would output {another:2} and the second would print {third: 3}. Indeed, this is the behavior I get when I run each test independently. e.g.

jeff@ubuntu:~/workspace/mocha-test$ mocha test/test2.js 

  { third: 3 }
․

  1 passing (6ms)

However, when running both test with npm packages should and mocha (1.16.1), I get the following output:

jeff@ubuntu:~/workspace/mocha-test$ mocha

  { another: 2 }
․․

  1 passing (6ms)
  1 failing

  1) some test messes up global:
     ReferenceError: test is not defined
      at Object.exports.exec (/home/jeff/workspace/mocha-test/lib/main.js:3:15)
      at Context.<anonymous> (/home/jeff/workspace/mocha-test/test/test2.js:8:10)
      at Test.Runnable.run (/usr/lib/node_modules/mocha/lib/runnable.js:211:32)
      at Runner.runTest (/usr/lib/node_modules/mocha/lib/runner.js:355:10)
      at /usr/lib/node_modules/mocha/lib/runner.js:401:12
      at next (/usr/lib/node_modules/mocha/lib/runner.js:281:14)
      at /usr/lib/node_modules/mocha/lib/runner.js:290:7
      at next (/usr/lib/node_modules/mocha/lib/runner.js:234:23)
      at Object._onImmediate (/usr/lib/node_modules/mocha/lib/runner.js:258:5)
      at processImmediate [as _immediateCallback] (timers.js:330:15)
like image 839
Jeff Allen Avatar asked Dec 23 '13 05:12

Jeff Allen


1 Answers

test2.js should be structured like this:

describe('some test', function(){
  before(function (){
    global.test = {third: 3};
  });

  it ('messes up global', function(){
    main.exec();
  })
});

travisjeffery on the GitHub issue mentioned in the comment explains:

mocha loads the files and then runs the suites, to reliably setup your tests the setup should be within the suite.

As @SB points out, this may not be amenable to sharing things like global variables across tests.

like image 198
Jeff Allen Avatar answered Nov 02 '22 06:11

Jeff Allen