如何使用Sinonjs存根Redis订阅频道?

时间:2016-11-29 14:43:12

标签: node.js sinon stub

我使用Redis

有一个简单的pub / sub
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事件回调,因此我可以将对象(如下所示)传递给msg参数

{
    "name":"testing"
}

1 个答案:

答案 0 :(得分: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
})