使用Sinon在javascript中存储Redis交互 [英] Stubbing Redis interactions in javascript using Sinon

查看:122
本文介绍了使用Sinon在javascript中存储Redis交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js工作。我的应用程序通过 node_redis 模块与Redis交互。我正在使用mocha和sinon自动测试我的应用程序。我的应用程序看起来像这样:

I am working in node.js. My app interacts with Redis via the node_redis module. I'm using mocha and sinon to automate testing of my app. My app looks something like this:

...snip
var redisClient = redis.createClient(redisPort, redisHost);
var someValue = redisClient.get("someKey");
return someValue;
....

我想将调用存根到redisClient.get()。要做到这一点,我还需要将调用存根到redis.createClient() - 我想......这是我的测试代码:

I want to stub the call to redisClient.get(). To do this I also need to stub the call to redis.createClient() - I think... Here's my test code:

...
var redis = require("redis");
var redisClient;
...
sinon.stub(redisClient, 'get').returns("someValue");
sinon.stub(redis, "createClient").returns(redisClient);
...
assert.equal(redis_client_underTest.call_to_redis(), "someValue");
...

测试失败, AssertionError:false = =someValue

如何存根 redisClient ,或者这是否均匀可能吗?

How do I stub out redisClient, or is this even possible?

推荐答案

你能做的就是使用像 Proxyquire Rewire 。我将使用重新连接作为示例。

What you could do is use something like Proxyquire or Rewire. I'll be using rewire for the example.

您想要存根的代码片段:

Your snippet of code you want to stub:

var redisClient = redis.createClient(redisPort, redisHost);
var someValue = redisClient.get("someKey");
return someValue;

然后在你的测试中你可以使用重新连线:

Then in your test you can use rewire:

var Rewire = require('rewire');

var myModule = Rewire("../your/module/to/test.js");

var redisMock = {
    get: sinon.spy(function(something){
             return "someValue";
         });
};

myModule.__set__('redisClient', redisMock);

这样你可以更换你的redisClient,你可以检查调用该函数的间谍。

This way you can have your redisClient replaced and you can check with the spy if the function was called.

这篇关于使用Sinon在javascript中存储Redis交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆