sinon.js存根 - 你可以在单个存根函数上调用多个回调吗?
如果我有一个带有2个回调的函数的存根,当调用存根函数时,如何将sinon.js连接到调用两个回调?
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?
例如 - 这里是我想要存根的函数,它将2个函数作为参数:
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 ...
}
我可以使用sinon来调用其中一个参数:
I can use sinon to call either one of the arguments:
stubbedThing.callsArg(0);
或
stubbedThing.callsArg(1);
但我似乎无法将两者都称为。如果我尝试:
stubbedThing.callsArg(0).callsArg(1);
或
stubbedThing.callsArg(0);
stubbedThing.callsArg(1);
然后sinon只会调用第二个参数。如果我按照其他顺序连接它,那么sinon将调用第一个arg。但是,我希望两者都被一个接一个地调用。
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.
这不是一个经典的场景,因为不是很多方法会顺序调用两个方法,我猜这就是为什么它不受支持。但是,要保持冷静,解决方案很简单:
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'); });
旁注:这也提供了选择是否应首先调用一个或两个的选项。