2016-11-29 35 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

只是更新答案。 –