express - 在 Express 中使用 supertest 时如何模拟 redis?

标签 express redis mocking supertest

我正在 Express 中构建一个 REST API,我试图在我的 Jasmine 单元测试中模拟 Redis(使用 redis-mock)。

如果 supertest 正在向 API 发出请求,我如何告诉我的应用程序使用模拟 Redis 而不是实际的 Redis? .我知道我可能需要为我可以以某种方式换出的 redis 创建单独的模块,只是不确定如何将其换出以用于常规请求和 super 测试请求。

单元测试:

describe('Instance API v1', () => {
    it('returns a list of instances', (done) => {
        request(app.default)
            .get('/v1/instance')
            .set('Authorization', 'Bearer '+authToken)
            .expect(200)
            .expect('Content-Type', 'application/json; charset=utf-8')
            .end((error) => (error) ? done.fail(error) : done());
    });
});

路由处理器:

 getAll = (request: express.Request, response: express.Response) => {
        let redis: RedisClient = request.app.locals.redisclient;

        let keys:string[] = [];
        let prefix = 'instance/*';

        const scanner = new RedisScan(redis);

        scanner.scan('instances/*', (err, matchingKeys) => {
            if (err) throw(err);

            // matchingKeys will be an array of strings if matches were found
            // otherwise it will be an empty array.
            console.log(matchingKeys);

            response.json(matchingKeys);


        });
    };

最佳答案

根据我以前的经验,我没有在集成测试中模拟 Redis,所以我可以测试完整功能的流程。

如果你想模拟 Redis,你必须在你要求之前这样做,并在测试中启动你的应用程序,如下所示:

before(function() {
  const matchingKeys = '1234'; 
  sinon.stub(RedisScan.prototype, 'scan').yields(null, matchingKeys);

  const app = require('./app');
  return app.init(); // your init or whatever function to initiate your express app
});

希望对你有帮助

关于express - 在 Express 中使用 supertest 时如何模拟 redis?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134390/

相关文章:

.Net - 模拟和混淆

c# - 是否可以针对任意输入训练 Rhinomocks?

php - UnitTest 对象模拟或真实对象

javascript - 在 ExpressJS 中将变量发送到路由器

javascript - 类实例的未定义​​返回 - Javascript

node.js - 数据库中的 HTML 显示为纯文本

Redis对内存的消耗

node.js - 将node_modules或bower_components复制到Web应用程序中的static/public目录

sinatra - resque worker 负载分配不公平

spring-boot - Spring Boot redisTemplate Autowiring 失败