I have NestJS app with ioredis module. Me need to create test for my services who use Redis Service(code below). With start test, my project aslo startring. But in other test without Redis Service my project does starting, and running only test.
Maybe my Redis Service is wrong? If i delete this code this.client = new Redis.Cluster(hosts, {...}) my test running witout all project. I try to use ioredis-mock, but it didn't work.
import * as Redis from 'ioredis';
import { Injectable, Logger } from '@nestjs/common';
import {
REDIS_HA_URL,
REDIS_HA_PASSWORD,
REDIS_PORT,
} from '../config/config.service';
@Injectable()
export class RedisService {
private logger = new Logger('Redis Service');
client;
constructor() {
const hosts = REDIS_HA_URL.map(element => ({ host: element, port: REDIS_PORT }));
this.client = new Redis.Cluster(hosts, {
redisOptions: {
reconnectOnError() {
return 2;
},
password: REDIS_HA_PASSWORD,
},
});
this.client.on('error', (error: any) => {
this.logger.error(Redis error ${error});
});
this.client.on('reconnecting', () =>
this.logger.error(Redis reconnecting...),
);
}
}
I'm sure there's a more elegant way but you didn't give us much to go on...
Mock by creating your own MockedClient object that will respond as you want it to for testing, create a RedisServiceMock class of
and then in your unit test file, create an instance of RedisServiceMock and set up your test module to use it.