Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Node.js global variable in mocha tests

I have got a problem with mocha tests around global object I'm using with Node.js.

In index file, I set value to global variable

// index.js
global.enums = enumTemp

export default app

And then used it in another file

// other.js

status = global.enums.object.status

It's REST API and runs well if I made a request to a server. However, when I use a Mocha test, it seems to I cannot get the value for Node.js global variable. Any idea everyone?

like image 883
Toan Tran Avatar asked Jul 12 '17 04:07

Toan Tran


People also ask

How do I use global variables in NodeJS?

To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value.


1 Answers

I have found a solution that works for me by using Mocha hooks to set global variable just for testing:

// setup.test.js
import MyFunc from '../helpers/my-func'

before((done) => {
  MyFunc.then((variable) => {
    global.variable = variable
    done()
  })
})

We can use the global.variable in the test just like in the real code.

like image 162
Toan Tran Avatar answered Oct 20 '22 19:10

Toan Tran