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

后端 未结 8 2080
我在风中等你
我在风中等你 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:25

    Mocking require feels like a nasty hack to me. I would personally try to avoid it and refactor the code to make it more testable. There are various approaches to handle dependencies.

    1) pass dependencies as arguments

    function underTest(innerLib) {
        return innerLib.doComplexStuff();
    }
    

    This will make the code universally testable. The downside is that you need to pass dependencies around, which can make the code look more complicated.

    2) implement the module as a class, then use class methods/ properties to obtain dependencies

    (This is a contrived example, where class usage is not reasonable, but it conveys the idea) (ES6 example)

    const innerLib = require('./path/to/innerLib')
    
    class underTestClass {
        getInnerLib () {
            return innerLib
        }
    
        underTestMethod () {
            return this.getInnerLib().doComplexStuff()
        }
    }
    

    Now you can easily stub getInnerLib method to test your code. The code becomes more verbose, but also easier to test.

提交回复
热议问题