在Express中使用超级测试时,如何模拟Redis?

时间:2019-01-10 17:54:37

标签: express redis mocking supertest

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

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

单元测试:

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);


        });
    };

1 个答案:

答案 0 :(得分:0)

在我以前的经验,我没有在集成测试嘲笑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
});

希望有帮助