Sinon stub 包含同步和异步函数的对象

Sinon stub an object containing sync and async functions

我正在做一个项目,我正在观察 node.js javascript 层调用的每个绑定层函数的类型。为了观察类型,我使用 sinon 创建了一个存根,看起来像这样

var originalProcessBinding = process.binding;
sinon.stub(process, 'binding').callsFake(function (data) {
  var res = originalProcessBinding(data);
  // custom code here
  return res;
}

所以,我的想法是查看 res 中的每个 object,看看它是否是 Function。如果是,则创建一个记录状态的存根,然后调用原始Functioncustom code 看起来像

_.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);
    }
  }
}

但是,我不确定这是否处理所有类型的 returns。例如,如何处理错误?如果函数是异步的会发生什么?

我运行 node.js 测试套件发现了很多失败的测试用例。有没有更好的方法来存根函数。谢谢。

编辑:失败的测试用例有类似 Callback was already calledTimeoutExpected Error.

的共同错误

不幸的是,即使可以修复许多错误,也很难将 sinon 添加到构建过程中。我在 vanilla js 中通过自己的存根方法来解决这个问题。任何想要存根内部 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 的当前 master 的所有测试。添加 sinon 似乎会改变触发内部 v8 检查失败的函数对象。