我正在 nodejs 中创建一个小项目,它是 API 的包装器。我正在使用 nodeunit 编写一些单元测试并且需要将各种模拟函数注入(inject)模块(例如模拟向服务器发出 HTTP 请求并输出各种不同响应以测试我的代码的函数)。
我的问题是如何将这些函数注入(inject)到我的模块中?
我已经确定了两种理论上应该起作用的方法,如下所示:
方法一
重命名我要替换的模块的文件夹,并添加一个包含我要注入(inject)的代码的新文件夹,例如:
./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 对象
- 遍历 this._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?
*/
是否有更好的方法在我的模块中注入(inject)/替换功能以进行测试?
最佳答案
关于javascript - 用模拟函数替换 nodejs 模块中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31763562/