我正在 nodejs 中创建一个小项目,它是 API 的包装器。我正在使用nodeunit编写一些单元测试,并且需要将各种模拟函数注入到模块中(例如,一个模拟向服务器发出 HTTP 请求并输出各种不同响应以测试我的代码的函数)。
我的问题是如何将这些功能注入到我的模块中?
我已经确定了两种理论上应该起作用的方法,如下所示:
方法一
重命名我要替换的模块的文件夹并添加一个包含我要注入的代码的新文件夹,例如:
./node_modules/request -> ./node_modules/request.tmp
./tests/myRandomFunction -> ./node_modules/request
执行测试后,我会做相反的事情:
./node_modules/request -> ./tests/myRandomFunction
./node_modules/request.tmp -> ./node_modules/request
这似乎很老套,即使理论上应该可行,我也不想尝试。
方法二
这是我使用模块初始化的首选方法。我的模块采用一个 JSON 对象,该对象可以包含如下各种选项:
var module = require('./module')({
option1: '',
option2: '',
...
});
我计划向这个名为“_testing”的 JSON 对象添加一个键,其值为包含各种函数的 JSON 对象,例如:
var module = require('./module')({
_testing: {
request: function() {return false;}
}
});
在我的模块中,我可以执行以下操作:
- 如果 this._testing 存在并且是一个 JSON 对象
- 循环这个._testing
- 对于 this._testing 中的每个键
- 将与键同名的函数替换为其值,例如
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?
*/
有没有更好的方法来注入/替换我的模块中的函数以进行测试?