How to unit test 'private' utility function in nodejs

后端 未结 2 1282
甜味超标
甜味超标 2021-02-07 06:40

I\'m currently writing some tests for a nodejs application. assume that I have a module like this:

module.exports = function myModule(moduleParam) {
    var some         


        
2条回答
  •  借酒劲吻你
    2021-02-07 07:14

    Since i find tests to be a useful tool beyond unit testing and TDD (this SO answer makes a good argument), I made an npm package to help in cases like yours: require-from.

    In you example this is how you would use it:

    module-file.js:

    function helper(param) {
        return param + someVar;
    }
    
    module.exports = function myModule(moduleParam) {
        var someVar;
        ....
        ....
        return {
            doSomething: function (bar) {
                ....
                ....
                var foo = helper(bar);
                ....
                ....
            }
        };
    };
    module.helperExports = helper;
    

    importing-file.js:

    var requireFrom = require('require-from');
    var helper = requireFrom('helperExports', './module-file'));
    var public = requireFrom('exports', './module-file')); // same as require('./module-file')
    

提交回复
热议问题