我正在开发一个项目,在该项目中我观察 Node.js javascript 层调用的每个绑定(bind)层函数的类型。为了观察类型,我使用 sinon
创建了一个 stub ,看起来像这样
var originalProcessBinding = process.binding;
sinon.stub(process, 'binding').callsFake(function (data) {
var res = originalProcessBinding(data);
// custom code here
return res;
}
所以,我的想法是查看 res
中的每个对象
,看看它是否是一个函数
。如果是,则创建一个记录状态的 stub ,然后调用原始函数。 自定义代码
看起来像
_.forEach(res, function(value, key) {
if (_.isFunction(value)) {
sinon.stub(res, key).callsFake(function() {
var args = arguments;
// do some processing with the arguments
save(args);
// call the original function
return value(...arguments);
}
}
}
但是,我不确定这是否可以处理所有类型的返回。例如,如何处理错误?如果函数是异步的,会发生什么?
我运行了 node.js
测试套件,发现了很多失败的测试用例。有没有更好的方法来 stub 函数。谢谢。
编辑:失败的测试用例有一些共同的错误,例如回调已被调用
或超时
或预期错误
。
最佳答案
不幸的是,尽管可以修复许多错误,但很难将 sinon
添加到构建过程中。我在 vanilla js 中通过自己的 stub 方法实现来解决这个问题。任何想要 stub 内部 node.js
函数的人都会发现这很有帮助。
(function() { process.binding = function(args) {
const org = process.binding;
const util = require('util');
var that = org(args),
thatc = that;
for (let i in thatc) {
if (util.isFunction(thatc[i]) && (!thatc[i].__isStubbed)) {
let fn = thatc[i];
if (i[0] !== i[0].toUpperCase()) {
// hacky workaround to avoid stubbing function constructors.
thatc[i] = function() {
save(arguments);
return fn.apply(that, arguments);
}
thatc[i].__isStubbed = true;
}
}
}
return thatc;
}
})();
这段代码通过了当前 Node.js 大师的所有测试。添加 sinon 似乎会改变触发内部 v8 检查失败的函数对象。
关于javascript - Sinon stub 一个包含同步和异步函数的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48896890/