How to unit test a Node.js module that requires other modules and how to mock the global require function?

后端 未结 8 2068
我在风中等你
我在风中等你 2020-11-29 16:38

This is a trivial example that illustrates the crux of my problem:

var innerLib = require(\'./path/to/innerLib\');

function underTest() {
    return innerLi         


        
8条回答
  •  醉梦人生
    2020-11-29 17:26

    You can't. You have to build up your unit test suite so that the lowest modules are tested first and that the higher level modules that require modules are tested afterwards.

    You also have to assume that any 3rd party code and node.js itself is well tested.

    I presume you'll see mocking frameworks arrive in the near future that overwrite global.require

    If you really must inject a mock you can change your code to expose modular scope.

    // underTest.js
    var innerLib = require('./path/to/innerLib');
    
    function underTest() {
        return innerLib.toCrazyCrap();
    }
    
    module.exports = underTest;
    module.exports.__module = module;
    
    // test.js
    function test() {
        var underTest = require("underTest");
        underTest.__module.innerLib = {
            toCrazyCrap: function() { return true; }
        };
        assert.ok(underTest());
    }
    

    Be warned this exposes .__module into your API and any code can access modular scope at their own danger.

提交回复
热议问题