Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

javascript - 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.

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:

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...