使用sinon桩非导出函数

10
我为我的模块的doB函数编写了一个单元测试。
我想要在不导出它的情况下存根函数doA,我更喜欢不改变doB访问doA的方式。
我知道它不能简单地被存根,因为它不在导出的对象中。
如何存根doA(使用sinon或任何其他工具)?
function doA (value) {
   /* do stuff */
}

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

module.exports = exports = {
   doB
}
3个回答

3
我也使用了rewire。这是我想出来的东西。
const demographic = rewire('./demographic')

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

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

demographic.__set__('getDemographics', stubGetDemographics);

希望这可以帮助到您。

它说“get”不是一个函数,我们是否需要特定的JS版本才能使用此函数? - Taher Ghulam Mohammed
你是否使用rewire来导入模块?你有在这里检查例子吗:https://github.com/jhnns/rewire? - mikey
1
是的,现在它正在工作,我之前做错了。感谢您的帮助。 - Taher Ghulam Mohammed
1
在这段代码中,我认为 reqire 应该是 rewire - benevolentprof

1
我最终使用了rewire,我可以直接从模块中__get__一个内部函数,并使用sinon stub进行替换,或者使用rewire__with__实用程序来调用一个带有替换内部值的函数。

嗨,我正在尝试相同的方法...但运气不太好,你能分享一下你所做的代码片段吗? - mikey
@mikey,很抱歉我无法再访问代码了 :( - agoldis
没事了!我设法解决了,也许我会在这里发布我的答案!!不管怎样,谢谢@agoldis - mikey
@mikey,你能分享一下未导出函数的存根吗? - Nazeer_hanne

1
实际上,如果您不关心获取原始函数,而只是想要存根它,那么第一部分是不必要的。您可以改为这样做:
function stubPrivateMethod(modulePath, methodName) {
    const module = rewire(modulePath);
    
    const stub = sinon.stub();

    module.__set__(methodName, stub);

    return stub;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接