[node][mocha]使用 mocha 测试时无法访问全局变量

2024-05-24

我正在尝试为快速节点应用程序创建单元测试。 我希望用于测试的配置与生产中使用的配置不同,因此我实现了以下内容。

In my index.js,我将配置加载到全局变量中,如下所示:

global.env = {};
global.env.config = require('./config/config');
// Create the server ...
server.listen(3000);

module.exports = server;

在其他一些控制器中myController.js,我像这样访问全局变量

var Config = global.env.config

当我使用启动它时node index.js它工作得很好。

但是当我使用 mocha 和 proxyquire 来覆盖配置时:

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无法读取属性配置

Cannot read property 'config' of undefined

感谢您的帮助


这就是我的处理方式。首先,我会将配置导出为函数而不是对象。

原因是代码将具有更好的结构并且易于维护。 此外,无需全局公开配置,因为这可能会带来一些安全风险。

export const getConfig = () => {
  if(process.env.NODE_ENV==="production"){
    return require('./production.config');
  }
  return require('./default.config');
};

在我的测试文件中,我将使用以下方式模拟函数调用sinonjs像下面这样。

const configModule = require("./config");
sinon.stub(configModule, "getConfig").returns(require('./e2e.config'));

这不是经过测试的代码,但我有点确定这种思维模式应该有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[node][mocha]使用 mocha 测试时无法访问全局变量 的相关文章

随机推荐