import redis from 'redis'; import { RedisModuleOptions } from './redis.module'; import { RedisService } from './redis.service'; const mockClient = {}; const createClient = jest.fn().mockReturnValue(mockClient); jest.mock('redis', () => ({ createClient: (...args: any[]) => createClient(...args), })); describe(RedisService, () => { const conf: RedisModuleOptions = { url: 'foo://bar' }; const mockRedisClient = { connect: jest.fn().mockResolvedValue(undefined), quit: jest.fn().mockResolvedValue(undefined), }; let redisService: RedisService; describe(RedisService.prototype.connect, () => { beforeEach(() => { createClient.mockReset().mockReturnValue(mockRedisClient); redisService = new RedisService(conf); redisService.disconnect = jest.fn().mockResolvedValue(undefined); }); it('returns an existing client if options are not provided and a client exists', async () => { redisService['client'] = mockRedisClient as unknown as ReturnType; await expect(redisService.connect()).resolves.toBe(mockRedisClient); expect(createClient).not.toHaveBeenCalled(); expect(mockRedisClient.connect).not.toHaveBeenCalled(); }); it('creates a new client using the services config if config is not provided', async () => { await expect(redisService.connect()).resolves.toBe(mockRedisClient); expect(createClient).toHaveBeenCalledWith(conf); expect(mockRedisClient.connect).toHaveBeenCalled(); }); it('creates a new client with the config provided when calling the function even if a client already exists', async () => { const existingClient = { ...mockRedisClient }; const newConf = { ...conf, host: '' }; redisService['client'] = existingClient as unknown as ReturnType; const result = await redisService.connect(newConf); expect(result).toBe(mockRedisClient); expect(result).not.toBe(existingClient); expect(createClient).toHaveBeenCalledWith(newConf); expect(mockRedisClient.connect).toHaveBeenCalled(); expect(redisService.disconnect).toHaveBeenCalled(); }); }); describe(RedisService.prototype.disconnect, () => { beforeEach(() => { redisService = new RedisService(conf); }); it('calls quit on the existing client and sets the services client to null', async () => { redisService['client'] = mockRedisClient as unknown as ReturnType; await expect(redisService.disconnect()).resolves.toBe(undefined); expect(mockRedisClient.quit).toHaveBeenCalled(); expect(redisService['client']).toBeFalsy(); }); it('does nothing if there is not an existing client', async () => { redisService['client'] = undefined; await expect(redisService.disconnect()).resolves.toBe(undefined); }); }); });