如何在Mocha测试中要求相同的文件 [英] How to require same file in Mocha test

查看:45
本文介绍了如何在Mocha测试中要求相同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有config/index.js,它根据设置的NODE_ENV环境变量返回一个不同的配置文件.

I have config/index.js which returns a different config file based on the NODE_ENV environment variable that is set.

我正在尝试编写一个简单的测试以确保为每个环境返回正确的配置,但是我遇到了一个问题,其中实际上仅调用第一个需求,而随后使用同一文件来自第一个需求的值.

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();
  });
});

这是config/index.js的简化版本(可以正常工作),我正在尝试测试:

And here is a simplified version of config/index.js (which is working fine), that I'm trying to test:

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;

推荐答案

在运行第二项测试之前,我将从Node的模块缓存中删除该模块:

I would delete the module from Node's module cache before running the 2nd test:

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

因此,当再次需要它时,Node将从头开始加载.请注意,上面的代码只会从缓存中删除config模块.如果您需要删除require调用 inside 您的config模块加载的模块,那么对于每个模块,您都必须执行与上述相同的操作.

So when requiring it again, Node will load from scratch. Note that the code above will only delete the config module from the cache. 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.

顺便说一句,如果您的测试将变得异步,则需要像当前一样的done回调.如果您的测试要保持现在的同步,则可以将done从您提供给it的回调的参数列表中删除,并忽略调用它.

By the way, if your tests are going to become asynchronous, the you need the done callback like you currently have. 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.

这篇关于如何在Mocha测试中要求相同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆