7

I understand that global variables are bad but I want to use one.

excerpt from package.json:

"scripts": {
  "start": "nodemon jobsServer.js",
  "test": "cross-env NODE_ENV=test ./node_modules/.bin/istanbul cover -x \"**/*.spec.js\" ./node_modules/mocha/bin/_mocha -- jobs js --recursive -R spec"
},

jobsServer.js:

global.appPath = require('app-root-path');
// more code here

Now I want to be able to access appPath anywhere in the app.

When I run npm start it picks up the global variable and I am happy.

But when I run npm test it does not load the global (since the global is defined in the server file) and therefore all references to appPath break.

I DO NOT want to do:

const appPath = require('app-root-path');

In every single .spec.js test file.

How can I load the global variable for every spec file?

Louis
  • 146,715
  • 28
  • 274
  • 320
danday74
  • 52,471
  • 49
  • 232
  • 283

2 Answers2

16

You just need to add a setup file in test/mocha.opts that will be loaded before to start any test, then you will be available to access those global variables, for example:

test/mocha.opts

--require should
--require ./test/setup
--ui bdd
--globals global
--timeout 200

test/setup.js

global.app = require('some-library')
global.window = {}
global.window.document = {}

docs:

http://unitjs.com/guide/mocha.html#mocha-opts

danday74
  • 52,471
  • 49
  • 232
  • 283
damianfabian
  • 1,681
  • 12
  • 16
  • Note: Since Mocha v8.0.0 `mocha.opts` is no longer supported, and was replaced with a `mocharc` configuration file (`.mocharc.json`, `.mocharc.yaml`, `.mocharc.js`, etc) – e1v May 04 '23 at 14:03
2

You could probably write a module to hold your globals and import it in your test:

import getGlobals from './whatever.globals.spec.mjs';

...

describe('Whatever', () => {
    it('test global', () => {
      const globals = getGlobals();
      ...
  });

Where whatever.globals.spec.mjs is just :

export default function getGlobals() {
  return ...; // your global info
}
cquezel
  • 3,859
  • 1
  • 30
  • 32