Stub out module function

后端 未结 4 1134
粉色の甜心
粉色の甜心 2021-02-13 21:07

Edit: Being a little bit more precise.

I want to test usecases for a Github API wrapper extension, that our team has created. For testing, we don\'t want to use API wrap

4条回答
  •  礼貌的吻别
    2021-02-13 21:55

    I found that this worked for me...

    const sinon          = require( 'sinon' );
    const moduleFunction = require( 'moduleFunction' );
    
    //    Required modules get added require.cache. 
    //    The property name of the object containing the module in require.cache is 
    //    the fully qualified path of the module e.g. '/Users/Bill/project/node_modules/moduleFunction/index.js'
    //    You can get the fully qualified path of a module from require.resolve
    //    The reference to the module itself is the exports property
    
    const stubbedModule = sinon.stub( require.cache[ require.resolve( 'moduleFunction' ) ], 'exports', () => {
    
        //    this function will replace the module
    
        return 'I\'m stubbed!';
    });
    
    // sidenote - stubbedModule.default references the original module...
    

    You have to make sure that you stub the module (as above) before it's required elsewhere...

    // elsewhere...
    
    const moduleFunction = require( 'moduleFunction' ); 
    
    moduleFunction();    // returns 'I'm stubbed!'
    

提交回复
热议问题