简体   繁体   中英

Stubbing non-exported function with sinon

I write a unit-test for doB function of my module.

I want to stub the function doA without exporting it, I prefer not change the way doB accesses doA .

I understand that it cannot be simply stub ed because it isnt in the exported object.

How do I stub doA ( sinon or any other tool?)

function doA (value) {
   /* do stuff */
}

function doB (value) {
  let resultA = doA(value);
  if (resultA === 'something') {
     /* do some */
  } else {
     /* do otherwise */
  }
}

module.exports = exports = {
   doB
}

I did it using rewire too. This is what I came up with

const demographic = rewire('./demographic')

const getDemographicsObject = { getDemographics: demographic.__get__('getDemographics') };

const stubGetDemographics = sinon
 .stub(getDemographicsObject, 'getDemographics')
 .returns(testScores);

demographic.__set__('getDemographics', stubGetDemographics);

Hope this helps

我已经结束了使用ReWire的,我可以只__get__从模块的内部函数和stub与它sinon或使用rewire__with__实用程序来调用一个函数替换为内部值

Actually, if you don't care about fetching the original function, but rather just want to stub it, the first part is unnecessary. You can do something like this instead:

function stubPrivateMethod(modulePath, methodName) {
    const module = rewire(modulePath);
    
    const stub = sinon.stub();

    module.__set__(methodName, stub);

    return stub;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM