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

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

    I use mock-require. Make sure you define your mocks before you require the module to be tested.

    0 讨论(0)
  • 2020-11-29 17:39

    You can use mockery library:

    describe 'UnderTest', ->
      before ->
        mockery.enable( warnOnUnregistered: false )
        mockery.registerMock('./path/to/innerLib', { doComplexStuff: -> 'Complex result' })
        @underTest = require('./path/to/underTest')
    
      it 'should compute complex value', ->
        expect(@underTest()).to.eq 'Complex result'
    
    0 讨论(0)
提交回复
热议问题