如何在单元测试运行中初始化全局变量? [英] How to initialise a global variable in unit test runs?
问题描述
我知道全局变量很糟糕,但我想使用一个。
I understand that global variables are bad but I want to use one.
摘自package.json:
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:
jobsServer.js:
global.appPath = require('app-root-path');
// more code here
现在我希望能够在任何地方访问appPath app。
Now I want to be able to access appPath anywhere in the app.
当我运行 npm start
时,它会选择全局变量,我很高兴。
When I run npm start
it picks up the global variable and I am happy.
但是当我运行 npm test
时,它不会加载全局(因为全局是在服务器文件中定义的),因此所有引用appPath break。
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.
我不想这样做:
const appPath = require('app-root-path');
在每个单独的.spec.js测试文件中。
In every single .spec.js test file.
如何为每个spec文件加载全局变量?
How can I load the global variable for every spec file?
推荐答案
您只需要添加一个安装文件test / mocha.opts将在开始任何测试之前加载,然后您将可以访问这些全局变量,例如:
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
test/mocha.opts
--require should
--require ./test/setup
--ui bdd
--globals global
--timeout 200
test / setup.js
test/setup.js
global.app = require('some-library')
global.window = {}
global.window.document = {}
docs:
http://unitjs.com/guide/mocha.html#mocha-opts
这篇关于如何在单元测试运行中初始化全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!