所以我有一个场景,我试图为一个依赖于另一个mongodb仓库实现的mongodb仓库编写一个单元。假设我们在NestJS中有以下mongoose仓库和模块:
1.用户仓库
@Injectable()
export class UsersRepository extends EntityRepository<UserDocument> {
constructor(@InjectModel(User.name) userModel: Model<UserDocument>) {
super(userModel)
}
}
@Module({
imports: [
MongooseModule.forFeature(
[{ name: User.name, schema: UserSchema }],
'TEST-V2',
),
OrderModule,
],
controllers: [UserController],
providers: [UserService, UserRepository],
exports: [UserService, UserRepository],
})
export class UserModule {}
1.订单仓库
@Injectable()
export class OrdersRepository extends EntityRepository<OrderDocument> {
constructor(@InjectModel(Order.name) orderModel: Model<OrderDocument>) {
super(orderModel)
}
}
@Module({
imports: [
MongooseModule.forFeature(
[{ name: Order.name, schema: OrderSchema }],
'TEST-V2',
),
],
providers: [OrderService, OrderRepository],
exports: [OrderService, OrderRepository],
})
export class OrderModule {}
UserRepository有一个方法,比如'getOrders',它使用OrdersRepository从数据库中获取现有订单:
@Injectable()
export class UsersRepository extends EntityRepository<UserDocument> {
constructor(
@InjectModel(User.name) userModel: Model<UserDocument>,
protected readonly orderRepository: OrdersRepository
) {
super(userModel)
}
async getOrders(id: string) {
const orders = await this.orderRepository.find({ userId: id });
}
}
如何创建一个仓库依赖于另一个仓库的单元?这就是我想象的开始:
describe('TaskConfigRepository', () => {
let userModel: UserModel;
let userRepository: UserRepository;
let orderRepository: OrdersRepository;
let orderModel: OrderModel;
let connection: Connection;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
validationSchema: envVarValidationSchema,
isGlobal: true,
cache: true,
envFilePath: `.env`,
validationOptions: {
allowUnknown: true,
abortEarly: false,
},
load: [configuration],
}),
MongooseModule.forRootAsync({
connectionName: 'TEST-V2',
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
uri: configService.get('db.mongo.testv2'),
}),
}),
],
providers: [
UsersRepository,
OrdersRepository,
{
provide: getModelToken(Order.name),
useClass: OrderModel,
},
{
provide: getModelToken(User.name),
useClass: UserModel,
},
],
}).compile();
...
connection = await moduleRef.get(getConnectionToken('TEST-V2')
jest.clearAllMocks();
})
afterEach(async () => {
await connection.close();
});
})
当我向依赖项中添加第二个模型/存储库时,会有一种情况,即connection.close()
被认为是未定义的。
1条答案
按热度按时间m0rkklqb1#
如果UserRepository已注入OrderRepository
所以你的UserRepository模型应该有OrderModule在里面作为Import,所以现在要测试你应该首先使用经典的await Test.createTestingModule({......然后添加就像你通常会做的依赖,让我知道如果我得到了它的权利