Stubbing async.waterfall with Sinon.JS

Stubbing async.waterfall with Sinon.JS

本文关键字:Sinon JS with waterfall async Stubbing      更新时间:2023-09-26

我试图通过使用Sinon.js存根我的一个函数来测试async.waterfall

// functions.js
module.exports = {
  // function I don't want to run
  doBigThing: function() {
    console.log("[doBigThing] was called");
  },
  // function I want to stub
  myFunction: function(number, callback) {
    console.log("[myFunction] was called");
    doBigThing();
    callback(null, number);
  },
  // function I want to test
  waterfall: function(callback) {
    return async.waterfall([
      async.constant(5), // 5 just for the demo
      myFunction
    ], callback);
  }
}

我的测试是:

describe('water', function() {
  it ('successfully falls', function() {
    // function under test
    var waterfall = functions.waterfall;
    var callback = function(err, number) {
      expect(err).to.be.null;
      expect(number).to.equal(5);
    };
    // I would like this stub to run instead of functions.myFunction
    sinon.stub(functions, 'myFunction', function(number, callback) {
      console.log("[myFunction] stub was called");
      callback(null, number);
    });
    waterfall(callback);
    // I suppose this is happening: myFunction(5, callback) 
    expect(functions.myFunction.withArgs(5, callback)).to.have.been.called;
    expect(callback).to.have.been.called;
  });
});

因此,测试通过了,但存根被忽略,因为调用了doBigThing

  Water
    ✓ successfully falls
[myFunction] was called
[doBigThing] was called

相反,我希望看到

  Water
    ✓ successfully falls
[myFunction] stub was called

我可能错过了一些东西,我将不胜感激你的帮助。

您正在myFunction functions对象的方法存根,但是waterfall方法中您正在调用myFunction函数(我实际上无法在我的环境中运行您的代码,我得到"引用错误:未定义myFunction")。所以这应该有效:

// functions.js
var functions = {
  // function I don't want to run
  doBigThing: function() {
    console.log("[doBigThing] was called");
  },
  // function I want to stub
  myFunction: function(number, callback) {
    console.log("[myFunction] was called");
    functions.doBigThing(); // CHANGE HERE
    callback(null, number);
  },
  // function I want to test
  waterfall: function(callback) {
    return async.waterfall([
      async.constant(5), // 5 just for the demo
      functions.myFunction // CHANGE HERE
    ], callback);
  }
};
module.exports = functions;