gpt4 book ai didi

node.js - 在 Jest 中模拟 Redis - NestJS

转载 作者:行者123 更新时间:2023-12-05 05:46:30 26 4
gpt4 key购买 nike

我正在为我的 nestjs 应用程序使用 Redis 缓存,我正在为 Redis 配置维护 redisCache.module.ts。但是我的单元测试失败了,因为它正在尝试连接到 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();
});
});

错误

enter image description here

最佳答案

我通过覆盖 CACHE_MODULE_OPTIONS 来 mock 它。

这是我的一项端到端测试的示例:

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

关于node.js - 在 Jest 中模拟 Redis - NestJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71169241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com