How to unit test 'private' utility function in nodejs

后端 未结 2 1284
甜味超标
甜味超标 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:04

    You don't test it. Unit testing is black box testing. This means that the only thing you test is the public interface aka contract.

    Private functions such as these only can happen from refactoring public ones.

    So if you consequently use TDD your private functions are implicitly tested.

    If this feels wrong it's most often because your structure is wrong. Then you should think about moving your private stuff to an extra module.

    0 讨论(0)
  • 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')
    
    0 讨论(0)
提交回复
热议问题