首页 > 解决方案 > 使用 Jest 和 nestjs-typegoose 测试 InjectModel

问题描述

我的控制器有一个参数是 InjectModel,代码:

 constructor(
      @InjectModel(Poll) private readonly model: ReturnModelType<typeof Poll>,
  ){
 }

投票代码是:

import { prop, modelOptions, getModelForClass } from '@typegoose/typegoose';
import { ApiProperty, ApiPropertyOptions } from '@nestjs/swagger';

@modelOptions({
schemaOptions: {
timestamps: true
}
})
export class Poll {
@ApiProperty({

})
@prop({required: true})
title: string

@prop({required: true})
description: string

@prop()
poll: number

@prop({select: false})
userId: string

@prop()
userName: string

}

笑话代码:

import { Poll } from '@libs/db/models/poll.model';
const module: TestingModule = await Test.createTestingModule({
  imports: [PollsModule],
  controllers: [PollsController],
  providers: [
    {
      provide: getModelForClass(Poll),
      useValue: getModelForClass(Poll)
    },
  ]
}).compile();

我收到此错误:Nest 无法解析 PollsController (?) 的依赖项。请确保索引 [0] 处的参数 PollModel 在 PollsModule 上下文中可用。

Potential solutions:
- If PollModel is a provider, is it part of the current PollsModule?
- If PollModel is exported from a separate @Module, is that module imported within PollsModule?
  @Module({
    imports: [ /* the Module containing PollModel */ ]
  })

标签: jestjsnestjs

解决方案


poll 在全局模型中为“DbModel”,而 DbModel 在 appModel 中。所以testModel需要导入DbModel,然后修复!


推荐阅读