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?
In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known before the execution starts. An error will be generated if the constant values are not provided for global and static variables.
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With