如何在mocha测试中使用Node.js全局变量

Toa*_*ran 10 javascript testing mocha.js node.js

我在使用Node.js的全局对象周围进行了mocha测试.

在索引文件中,我将值设置为全局变量

// index.js
global.enums = enumTemp

export default app
Run Code Online (Sandbox Code Playgroud)

然后在另一个文件中使用它

// other.js

status = global.enums.object.status
Run Code Online (Sandbox Code Playgroud)

它是REST API,如果我向服务器发出请求,它运行良好.但是,当我使用Mocha测试时,似乎我无法获得该值Node.js global variable.大家好吗?

Toa*_*ran 12

我找到了一个适用于我的解决方案,通过使用Mocha挂钩来设置global variable测试:

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

before((done) => {
  MyFunc.then((variable) => {
    global.variable = variable
    done()
  })
})
Run Code Online (Sandbox Code Playgroud)

我们可以global.variable像在实际代码中一样使用测试.