sinon.js stub - can you call more than one callback on a single stubbed function?

☆樱花仙子☆ 提交于 2019-12-10 03:14:41

问题


If I have a stub for a function that takes 2 callbacks, how can I wire up sinon.js to call both callbacks when the stubbed function is invoked?

For example - here's function that I want to stub which takes 2 functions as arguments:

function stubThisThing(one, two) {
   ... one and two are functions ...
   ... contents stubbed by sinon.js ...
}

I can use sinon to call either one of the arguments:

stubbedThing.callsArg(0);

or

stubbedThing.callsArg(1);

but I can't seem to get both to be called. If I try:

stubbedThing.callsArg(0).callsArg(1);

or

stubbedThing.callsArg(0);
stubbedThing.callsArg(1);

then sinon will only ever call the second argument. If I wire it up in the other order, then sinon will call the first arg. However, I'd like both to be called one after the other.


回答1:


This is not a classic scenario, since not many methods would call two methods sequentially, and I guess thats why it isn't supported. But, be calm, the solution is easy:

var subject = { 
    method: function(one, two) {} 
};

var stub = sinon.stub(subject, 'method', function(one, two) { 
    one(); 
    two(); 
});

subject.method(
    function() { console.log('callback 1'); }, 
    function() { console.log('callback 2'); });

Side note: This also gives the option for choosing if one or two should be called first.




回答2:


Why don't you skip sinon altogether?

var obj = { stubMe: function(cb1, cb2) {} };
var originalMethod = obj.stubMe;

obj.stubMe = function(cv1, cb2) { 
  //Whatever logic you wish
  cb1(); 
  cb2(); 
}; 

//Do your test

obj.stubMe = originalMethod; //Restore

This way you can even continue to use sinon's APIs, if you wish:

var stub = sinon.stub();
obj.stubMe = function(cb1, cb2) { 
  stub.apply(stub, arguments);
  //Rest of whatever logic you wanted here
};

obj.stubMe();
expect(stub.calledOnce()).to.be(true); //That would pass

What'd you think?



来源:https://stackoverflow.com/questions/29818811/sinon-js-stub-can-you-call-more-than-one-callback-on-a-single-stubbed-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!