我正在尝试通过使用 async.waterfall 对我的功能之一进行测试来测试Sinon.js

// 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;
  });
});

因此测试通过了,但是 stub 被忽略了,因为doBigThing被调用了:
  Water
    ✓ successfully falls
[myFunction] was called
[doBigThing] was called

相反,我想看看
  Water
    ✓ successfully falls
[myFunction] stub was called

我可能错过了一些东西,感谢您的帮助。

最佳答案

您正在 stub functions对象的方法 myFunction,但是在waterfall方法中,您正在调用myFunction 函数(我实际上无法在我的环境中运行您的代码,我得到了“ReferenceError:未定义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;

09-25 18:29