使用callsArgWith
來實現此目的。
// a mock callback function with same arguments channel and msg
var cb = function (channel, msg){
console.log("this "+ channel + " is " + msg.name + ".");
}
// a mock sub object with same member function on
var sub = {
on: function(event_name, cb){ console.log("on " + event_name) },
};
// FIRST: call the mock function
sub.on("message", cb("channel", {"name":"not stub"}));
// -----------------------------------------
// prepare mock arguments
var my_msg = {"name":"stub"}
// stub object
var subStub = sub;
sinon.stub(subStub);
// passing mock arguments into the member function of stub object
subStub.on.callsArgWith(1, 'channel', my_msg);
// SECOND: call the stub function
sub.on('message', cb);
結果
this channel is not stub.
on message
this channel is stub.
注意:由於對象成爲存根,因此on message
不會在第二呼叫顯示。
[編輯]
因爲我沒有同樣的環境下,我嘲笑Redis的相關代碼,如果你需要在你的代碼中使用上述情況下,你可以試試這個。
const sub = redis.createClient()
sub.subscribe('my_channel')
var subStub = sub;
sinon.stub(subStub);
subStub.on.callsArgWith(1, 'my_channel', {"name":"testing"});
sub.on('message', (channel, msg) => {
//parse the msg object
})
不錯的解釋,但我仍然無法弄清楚如何存根redis回調 – Tim
只是更新答案。 –