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

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

    You can now!

    I published proxyquire which will take care of overriding the global require inside your module while you are testing it.

    This means you need no changes to your code in order to inject mocks for required modules.

    Proxyquire has a very simple api which allows resolving the module you are trying to test and pass along mocks/stubs for its required modules in one simple step.

    @Raynos is right that traditionally you had to resort to not very ideal solutions in order to achieve that or do bottom-up development instead

    Which is the main reason why I created proxyquire - to allow top-down test driven development without any hassle.

    Have a look at the documentation and the examples in order to gauge if it will fit your needs.

提交回复
热议问题