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?
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.
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.
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