用Sinon.JS来扼杀asynchronousstream水

我想通过使用Sinon.js来扼杀我的一个函数来testingasync.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); } } 

我的testing是:

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

所以testing通过,但存根被忽略,因为doBigThing被称为:

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

相反,我想看看

  Water ✓ successfully falls [myFunction] stub was called 

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

你是stubbing 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;