我正在 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/