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

查看:24
本文介绍了使用 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;

然后在你的测试中你可以使用 rewire:

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天全站免登陆