Sinon功能存根:如何称呼"own"?模块内部功能 [英] Sinon function stubbing: How to call "own" function inside module

查看:92
本文介绍了Sinon功能存根:如何称呼"own"?模块内部功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为node.js代码编写一些单元测试,并使用Sinon通过以下方式存根函数调用

I am writing some unit tests for node.js code and I use Sinon to stub function calls via

var myFunction = sinon.stub(nodeModule, 'myFunction');
myFunction.returns('mock answer');

nodeModule看起来像这样

module.exports = {
  myFunction: myFunction,
  anotherF: anotherF
}

function myFunction() {

}

function anotherF() {
  myFunction();
}

模拟显然适用于像nodeModule.myFunction()这样的用例,但是我想知道如何在用nodeModule.anotherF()调用时如何在anotherF()内部模拟myFunction()调用?

Mocking works obviously for use cases like nodeModule.myFunction(), but I am wondering how can I mock the myFunction() call inside anotherF() when called with nodeModule.anotherF()?

推荐答案

您可以稍微重构一下模块.这样.

You can refactor your module a little. Like this.

var service = {
   myFunction: myFunction,
   anotherFunction: anotherFunction
}

module.expors = service;

function myFunction(){};

function anotherFunction() {
   service.myFunction(); //calls whatever there is right now
}

这篇关于Sinon功能存根:如何称呼"own"?模块内部功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆