Mock Redis in Jest - NestJS

Viewed 415

I'm Using Redis cache for my nestjs Application and i'm maintaining redisCache.module.ts for Redis configuration.But my unit test has fail because,it's trying to connect into Redis server.How can i fix this issue?

redisCache.module.ts

import { Module, CacheModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import { RedisCacheService } from './redisCache.service';

@Module({
  imports: [
    CacheModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        store:redisStore, 
        host: configService.get('REDIS_HOST'),
        port: configService.get('REDIS_PORT'),
        ttl: configService.get('REDIS_CACHE_TTL'),
      }),
    }),
  ],
  providers: [RedisCacheService],
  exports: [RedisCacheService]
})
export class RedisCacheModule {}

redisCache.module.spec.ts

import { CacheModule, CACHE_MANAGER } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { RedisCacheService } from './redisCache.service';
import { RedisCacheModule } from './redisCache.module';
import { Cache } from 'cache-manager';

describe('RedisCacheModule', () => {
  let redisCacheService: RedisCacheService;
  let redisCacheModule: RedisCacheModule;
  let cache: Cache;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [RedisCacheService],
      imports: [CacheModule.register({}),RedisCacheModule],
    }).compile();

    redisCacheService = module.get<RedisCacheService>(RedisCacheService);
    redisCacheModule = module.get<RedisCacheModule>(RedisCacheModule);
    cache = module.get(CACHE_MANAGER);
  });

  it('RedisCacheService should be defined', () => {
    expect(redisCacheService).toBeDefined();
  });

  it('RedisCacheModule should be defined', () => {
    expect(redisCacheModule).toBeDefined();
  });
});

Error

enter image description here

1 Answers

I mocked this by overriding the CACHE_MODULE_OPTIONS.

Here is an example from one of my e2e tests:

const moduleFixture: TestingModule = await Test.createTestingModule({
  imports: [AppModule], // or whatever imports you need for your service/etc
})
  .overrideProvider(CACHE_MODULE_OPTIONS)
  .useValue({
    // your options go here (minus host and port and store), or you can leave as an empty object
  })
  .compile();

I got this answer from here when trying to figure out this same thing: https://github.com/nestjs/docs.nestjs.com/issues/681#issuecomment-1096939527

Related