综合技术

Is there a Java classpath-like feature for server-side Javascript?

微信扫一扫,分享到朋友圈

Is there a Java classpath-like feature for server-side Javascript?
0

When using JUnit and Maven in Java, one can have separate property files for src/main
and src/test
. This allows different configuration for code and tests, having Maven to manage the resources by using Java classpath.

Is there a similar way in Javascript code run by Node.js
? I use Mocha for unit-testing and Grunt for task management.

Code example for script.js
:

var config = require('./config/dev/app.js');

exports.getFileName = function() {
    return config.fileName; // returns 'code.txt'
}

What I need is to make the script.js
use different config file when being required in a test.js
unit test like this:

var assert = require('assert');
var s = require('./script.js');

describe('Test', function () {
    it('should use different config file', function() {
        assert.equal('test.txt', s.getFileName());
    });
});

Is there a way to use different configuration ./config/test/app.js
in the script.js
without having to alter the code of script.js
? What I really try to avoid is to adjust the code to support unit tests. Instead, I want to achieve similar functionality such as mentioned Java classpath.

Problem courtesy of: Pavel Lobodinský

Solution

I have not found any elegant solution out there on the web so I have implemented and published my own.
Check it out here: https://npmjs.org/package/app-config

Using the app-config
plugin, only the script.js
needs to get changed this way:

var config = require('app-config').app;

exports.getFileName = function() {
    return config.fileName; // returns 'code.txt'
}

The app needs to be run this way for example

NODE_ENV=dev node script.js
NODE_ENV=unitTest mocha test.js

Depending on the NODE_ENV
environmental variable, the right set of configuration files will be loaded by the app-config
plugin.

Solution courtesy of: Pavel Lobodinský

Discussion

Please try this code.

Script.js

var config;
if(process.env.dev===true){
   config = require('./config/dev/config.js');
}

if(process.env.prod===true){
   config = require('./config/prod/config.js');
}


exports.getFileName = function() {
    return config.fileName; // returns 'code.txt'
}

test.js

//set the environment here
process.env.dev = true;
var assert = require('assert');
var s = require('./script.js');

describe('Test', function () {
    it('should use different config file', function() {
        assert.equal('test.txt', s.getFileName());
    });
});

Discussion courtesy of: Chandu

This recipe can be found in it’s original form on Stack Over Flow
.

阅读原文...


微信扫一扫,分享到朋友圈

Is there a Java classpath-like feature for server-side Javascript?
0

Node.js Recipes

OMG My Master Is My Feature Branch

上一篇

一线丨华为7月将发布全新笔记本 启用新命名

下一篇

评论已经被关闭。

插入图片

热门分类

Is there a Java classpath-like feature for server-side Javascript?

长按储存图像,分享给朋友