Javascript 使用Sinon.JS stubing async.瀑布
我试图通过使用stub来测试我的一个函数 我的测试是:Javascript 使用Sinon.JS stubing async.瀑布,javascript,node.js,tdd,sinon,stubbing,Javascript,Node.js,Tdd,Sinon,Stubbing,我试图通过使用stub来测试我的一个函数 我的测试是: describe('water', function() { it ('successfully falls', function() { // function under test var waterfall = functions.waterfall; var callback = function(err, number) { expect(err).to.be.null; ex
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
我可能错过了一些东西,我会感谢你的帮助。你正在删除
函数
对象的方法我的函数
,但在瀑布
方法中,你调用的是我的函数
函数(我实际上无法在我的环境中运行你的代码,我明白了。)“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;
我正在运行代码,得到了您想要的结果:✓ 已成功调用[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;