Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise a global variable in unit test runs?

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?

like image 468
danday74 Avatar asked Jan 26 '17 13:01

danday74


People also ask

How do you initialize a global variable?

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.

How do you declare global variables in pho?

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.


1 Answers

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

like image 176
damianfabian Avatar answered Nov 15 '22 16:11

damianfabian