使用Jest在NestJS中模拟Redis

3

我正在为我的NestJS应用程序使用Redis缓存,并且我正在维护redisCache.module.ts以进行Redis配置。但是我的单元测试失败了,因为它正在尝试连接到Redis服务器。我该如何解决这个问题?

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();
  });
});

错误

输入图片描述

1个回答

3

我通过覆盖CACHE_MODULE_OPTIONS来进行模拟。

这是我其中一个端到端测试的示例:

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();

我在尝试解决同样的问题时从这里得到了答案:https://github.com/nestjs/docs.nestjs.com/issues/681#issuecomment-1096939527

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接