2016-11-29 10 views
0

私はSinonjsを使用してsub.onイベントコールバックスタブができ、私はmsg引数Sinonjsを使ってRedis購読チャンネルをスタブする方法は?

{ 
    "name":"testing" 
} 
に(下図参照)オブジェクトを渡すことができる方法を知っている可能性があり、私は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 
}) 

を使用して、単純なパブリッシュ/サブスクライブを持っています

答えて

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は、2番目の呼び出しでは表示されません。

[編集]私は同じ環境を持っていないので、私はあなたのコードで上記のケースを使用する必要がある場合、あなたはこれを試すことができ、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

いいえexplaination、しかし私はまだそれは赤いコールバックをスタブする方法を理解することができません – Tim

+0

ちょうど答えを更新します。 –

関連する問題