I am building an API powered by Express.js, it uses ioredis, it contains an ES6 class for configuring connections to a redis cluster:
import { Cluster } from 'ioredis';
import { settings } from '../config';
export class Redis
{
public cluster: Cluster;
public isConnected: boolean = false;
constructor() {
// Get array of rootNodes and default settings for each node
const { cluster } = settings.redis;
this.cluster = new Cluster(cluster.rootNodes, {
enableReadyCheck: true,
redisOptions: cluster.defaults
});
this.cluster.on('ready', () => {
console.log('Redis connection established, ready to receive commands');
this.isConnected = true;
});
this.cluster.on('error', (error) => {
console.log(`Redis connection error, status is ${this.cluster.status}`);
console.log(error.message);
});
this.cluster.on('close', () => {
console.log('Redis connection closed');
this.isConnected = false;
});
this.cluster.on('reconnecting', () => {
console.log('Reconnecting to redis cluster...');
});
}
}
export const redis = new Redis();
This class is used by a method which serves an API endpoint (simplified for brevity):
import { redis } from '../services/Redis';
...
async load(req: Request, res: Response) {
const data = <LoadGameRequest>req.params;
const gameID = data.gameId;
if (! redis.isConnected) {
throw new Error(`Redis connection is not established, status is ${redis.cluster.status}.`);
}
const game = await redis.cluster.get(gameID);
if (game !== 'OK') {
throw new Error('Result not OK. Unable to retrieve saved game.');
}
...
return res.status(200).send(game)
}
I want to implement tests, using supertest and jest/ts-jest. I have written a test for the endpoint above:
import supertest from 'supertest';
import app from '../app'; // the express app
describe('Test Game Load', () => {
test('It should return OK response', done => {
supertest(app).get('/api/load?gameId=1234').then(async (response) => {
expect(response.statusCode).toBe(200);
await done();
});
});
});
How do I mock my Redis
class within this context? I have tried using ioredis-mock
, but unfortunately I am a bit lost as to how exactly I replace the dependency in my app with the mocked version. I also tried to follow jest's documentation, but unfortunately I could not make an informed decision as to which path to follow.
Any help to point me in the right direction would be greatly appreciated, thank you.