我想为我的 Nestjs“类(class)”存储库服务(依赖于 Mongoose 模型和 Redis 的服务)编写单元测试。
类(class).repository.ts:
import { Injectable, HttpException, NotFoundException } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose"
import { Course } from "../../../../shared/course";
import { Model } from "mongoose";
import { RedisService } from 'nestjs-redis';
@Injectable({})
export class CoursesRepository {
private redisClient;
constructor(
@InjectModel('Course') private courseModel: Model<Course>,
private readonly redisService: RedisService,
) {
this.redisClient = this.redisService.getClient();
}
async findAll(): Promise<Course[]> {
const courses = await this.redisClient.get('allCourses');
if (!courses) {
console.log('return from DB');
const mongoCourses = await this.courseModel.find();
await this.redisClient.set('allCourses', JSON.stringify(mongoCourses), 'EX', 20);
return mongoCourses;
}
console.log('return from cache');
return JSON.parse(courses);
}
}
测试是这样初始化的:
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
MongooseModule.forRoot(MONGO_CONNECTION, {
useNewUrlParser: true,
useUnifiedTopology: true
}),
MongooseModule.forFeature([
{ name: "Course", schema: CoursesSchema },
{ name: "Lesson", schema: LessonsSchema }
]),
RedisModule.register({})
],
controllers: [CoursesController, LessonsController],
providers: [
CoursesRepository,
LessonsRepository
],
}).compile();
coursesRepository = moduleRef.get<CoursesRepository>(CoursesRepository);
redisClient = moduleRef.get<RedisModule>(RedisModule);
});
我的类(class)存储库服务有 2 个依赖项 - Redis 和 Mongoose 模型(类(class))。我想 mock 他们俩。
如果我 mock 一个提供者,我会使用该语法:
providers: [
{provide: CoursesRepository, useFactory: mockCoursesRepository},
LessonsRepository
],
我可以创建一个模拟 Redis 服务来代替测试期间的实际 Redis 服务吗?
如何?
谢谢,亚龙
请注意,接受的答案模拟了一个提供程序,如果它也是由 TestingModule
与提供程序一起提供的,则它将满足被测类的依赖关系。然而,它并没有按照要求模拟导入,这可能是不同的。例如。如果您需要导入
某个也依赖于模拟值的模块,则这将不起作用:
// DOES NOT WORK
const module = await Test.createTestingModule({
imports: [
ModuleThatNeedsConfig,
],
providers: [
{ provide: ConfigService, useValue: mockConfig },
ExampleService, // relies on something from ModuleThatNeedsConfig
]
}).compile();
要模拟导入
,您可以使用导出模拟值的DynamicModule
:
const module = await Test.createTestingModule({
imports: [
{
module: class FakeModule {},
providers: [{ provide: ConfigService, useValue: mockConfig }],
exports: [ConfigService],
},
ModuleThatNeedsConfig,
],
providers: [
ClassUnderTest,
]
}).compile();
由于这有点冗长,像这样的实用函数可能会有所帮助:
export const createMockModule = (providers: Provider[]): DynamicModule => {
const exports = providers.map((provider) => (provider as any).provide || provider);
return {
module: class MockModule {},
providers,
exports,
global: true,
};
};
然后可以这样使用:
const module = await Test.createTestingModule({
imports: [
createMockModule([{ provide: ConfigService, useValue: mockConfig }]),
ModuleThatNeedsConfig,
],
providers: [
ClassUnderTest,
]
}).compile();
这通常具有额外的好处,可以让您导入
被测类的模块,而不是让测试绕过模块并直接提供
值。
const module = await Test.createTestingModule({
imports: [
createMockModule([{ provide: ConfigService, useValue: mockConfig }]),
ModuleThatNeedsConfig,
ModuleUnderTest,
],
}).compile();
const service = module.get(ClassUnderTest);
我是一名优秀的程序员,十分优秀!