问题描述
我正在尝试为快速节点应用程序创建单元测试.我希望测试所用的配置与生产环境中所用的配置不同,因此我实现了以下内容.
I'm trying to create a unit test for express node application.I want the configuration used for the test to be different than the one used in production, so I implemented the following.
在我的 index.js
中,我将配置加载到全局变量中,如下所示:
In my index.js
, I load the configuration into the global variable like this:
global.env = {};
global.env.config = require('./config/config');
// Create the server ...
server.listen(3000);
module.exports = server;
在其他控制器 myController.js
中,我这样访问全局变量
In some other controller myController.js
, I access the global variable like this
var Config = global.env.config
当我使用 node index.js
启动它时,它就可以正常工作.
When I launch this using node index.js
it works just fine.
但是当我将mocha与proxyquire一起使用时,会覆盖配置:
But when I use mocha with proxyquire to override the config:
describe('myController', function () {
describe("#myMethod", () => {
it("must work", (done) => {
const config = {
INPUT_FILE_DIR: path.resolve('../ressources/input/')
}
const server = proxyquire('../index.js', { './config/config': config })// error in this line
})
})
})
我遇到一个错误,告诉我 myController
无法读取属性config
I have an error telling that myController
can't read the property config
Cannot read property 'config' of undefined
感谢您的帮助
推荐答案
这就是我的处理方式.首先,我将配置导出为函数而不是对象.
This is how I would have approached it. Firstly, i would export config as a function instead of an object.
原因是代码将具有更好的结构并且易于维护.此外,也无需全局公开配置,因为这可能会带来一些安全风险.
export const getConfig = () => {
if(process.env.NODE_ENV==="production"){
return require('./production.config');
}
return require('./default.config');
};
在我的测试文件中,我将使用 sinonjs
来模拟函数调用,如下所示.
In my test file, I would mock the function call using sinonjs
like below.
const configModule = require("./config");
sinon.stub(configModule, "getConfig").returns(require('./e2e.config'));
这不是经过测试的代码,但我可以肯定,这种思维模式应该可以工作.
This is not a tested code, but I a bit certain that this pattern of thought should work.
这篇关于[node] [mocha]使用mocha测试时无法访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!