Toan Tran Toan Tran - 1 year ago 106
Javascript Question

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 used Mocha test, it seems to be can not get value for
Node.js global variable
. Any idea everyone?

Answer Source

I have found solution 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

We can use the global.variable in the test as same as in the real code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download