2016-11-29 69 views
0

我使用Redis的如何使用Sinonjs存儲Redis訂閱頻道?

const sub = redis.createClient() 
sub.subscribe('my_channel') 

// I would like to stub this on event, so I can pass an object to the msg argument 
sub.on('message', (channel, msg) => { 
    //parse the msg object 
}) 

可我知道我該怎麼存根使用Sinonjs的sub.on事件回調簡單的pub/sub,這樣我就可以傳遞一個對象(如下圖所示)到msg參數

{ 
    "name":"testing" 
} 

回答

0

使用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 
}) 
+0

不錯的解釋,但我仍然無法弄清楚如何存根redis回調 – Tim

+0

只是更新答案。 –