用模拟函数replacenodejs模块中的函数
我正在创build一个包含API的nodejs中的小项目。 我正在使用nodeunit编写一些unit testing,并且需要向模块中注入各种模拟函数(例如模拟向服务器发出HTTP请求并输出各种不同响应以testing我的代码的函数)。
我的问题是如何将这些function注入到我的模块?
我已经确定了两个理论上应该如下工作的方法:
方法1
重命名我想要replace的模块的文件夹,并添加一个包含我想要注入的代码的新文件夹,例如:
./node_modules/request -> ./node_modules/request.tmp ./tests/myRandomFunction -> ./node_modules/request
进行testing后,我会做相反的事情:
./node_modules/request -> ./tests/myRandomFunction ./node_modules/request.tmp -> ./node_modules/request
这看起来很诡异,不是我想尝试的东西,即使理论上它应该工作。
方法2
这是我使用模块初始化的首选方法。 我的模块需要一个JSON对象,可以包含各种选项,如下所示:
var module = require('./module')({ option1: '', option2: '', ... });
我打算为这个名为'_testing'的JSON对象添加一个键,其中包含各种函数的JSON对象的值,例如:
var module = require('./module')({ _testing: { request: function() {return false;} } });
在我的模块中,我可以做到以下几点:
- 如果this._testing存在并且是一个JSON对象
- 循环this._testing
- 对于这个._testing中的每个键
- 用与其值相同的名称replace该函数的值,例如
eval(''+key+' = this._testing.'+key) //eval('request = this._testing.request') /* eval can be dangerous I should probably perform some validation for example is key a function we want to be replaced? Can I check if nodeunit is testing my module and if it isn't don't do anything? */
有没有更好的方法来注入/replace我的模块中的function进行testing?
为此,我使用了嘲笑
并testingHTTP调用Nock
他们都提供了一个更清洁的方法
这被称为“嘲弄”或“残留”。 testing时常见,而且还有各种各样的库。 可能最受欢迎的是锡诺 。
有了Sinon,你可以做var stub = sinon.stub(request, [methodName]).returns(false)
(或其他任何返回值)。 你也可以做stub.expects(42)
这样的事情来断言函数在被调用时接收到这个参数。