Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 stubed 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
}
like image 809
agoldis Avatar asked Jan 18 '17 13:01

agoldis


1 Answers

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

like image 153
mikey Avatar answered Nov 15 '22 00:11

mikey