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?
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?
Share Improve this question edited Mar 24, 2018 at 18:52 Louis 151k28 gold badges284 silver badges328 bronze badges asked Jan 26, 2017 at 13:02 danday74danday74 57k55 gold badges267 silver badges331 bronze badges 02 Answers
Reset to default 16You 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
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
}