简体   繁体   English

如何在Mocha测试中要求相同的文件

[英]How to require same file in Mocha test

I have config/index.js which returns a different config file based on the NODE_ENV environment variable that is set. 我有config/index.js ,它根据设置的NODE_ENV环境变量返回一个不同的配置文件。

I'm trying to write a simple test to ensure that the right config is returned for each environment, but I'm running into an issue where only the first require is actually be called and subsequent requires of the same file are using the value from the first require. 我正在尝试编写一个简单的测试以确保为每个环境返回正确的配置,但是我遇到了一个问题,其中实际上仅调用了第一个需求,而同一文件的后续需求正在使用来自首先要求。

How should I change my test to resolve this issue? 我应该如何更改测试以解决此问题?

describe('config', function () {

  it('should return dev config', function (done) {
    process.env.NODE_ENV = 'development';
    var config = require(__dirname + '/../../config'); // development config 

    console.log(config.plugins.ipFilter);
    done();
  });

  it('should return prod config', function (done) {
    process.env.NODE_ENV = 'production';

    // development config from above.
    // the require here doesn't actually get invoked
    var config = require(__dirname + '/../../config');

    console.log(config.plugins.ipFilter);
    done();
  });
});

And here is a simplified version of config/index.js (which is working fine), that I'm trying to test: 这是config/index.js的简化版本(工作正常),我正在尝试测试:

var Hoek = require('hoek');

var settings = {
  'defaults':     require('./settings/defaults'),
  'production':   require('./settings/production')
};

var env;
switch (process.env.NODE_ENV) {
  case 'production':  env = 'production';   break;
  case 'development': env = 'development';  break;
  default:            env = 'defaults';     break;
}

var config = Hoek.applyToDefaults(settings['defaults'], settings[env]);
module.exports = config;

I would delete the module from Node's module cache before running the 2nd test: 在运行第二项测试之前,我将从Node的模块缓存中删除该模块:

var resolved = require.resolve(__dirname + '/../../config');
delete require.cache[resolved];

So when requiring it again, Node will load from scratch. 因此,当再次需要它时,Node将从头开始加载。 Note that the code above will only delete the config module from the cache. 请注意,上面的代码只会从缓存中删除config模块。 If you need to delete the modules loaded by the require calls inside your config module, then you'll have to do the same as above for each of them too. 如果您需要删除config模块内部require调用加载的模块,则每个模块也必须执行与上述相同的操作。

By the way, if your tests are going to become asynchronous, the you need the done callback like you currently have. 顺便说一句,如果您的测试将变得异步,则需要像当前一样done回调。 If your tests are meant to remain synchronous as they are now, the you could remove done from the argument list of the callbacks you give to it and omit calling it. 如果您的测试要保持现在的同步,则可以从提供给it的回调的参数列表中删除done ,然后省略调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM