【问题标题】:NestJs failes to compile testing module when running tests with JestNestJs 在使用 Jest 运行测试时无法编译测试模块
【发布时间】:2021-05-30 16:15:07
【问题描述】:

我有一个CategoryService,它是CategoriesModule 的提供者:

@Module({
    imports: [
        MongooseModule.forFeatureAsync([
            {
                name: Category.name,
                imports: [EventEmitterModule],
                inject: [EventEmitter2],
                useFactory: (eventEmitter: EventEmitter2) => {
                    const schema = CategorySchema
                    schema.post('findOneAndDelete', (category: CategoryDocument) => eventEmitter.emit(CollectionEvents.CategoriesDeleted, [category]))
                    return schema
                }
            }
        ])
    ],
  providers: [CategoriesService]
})
export class CategoriesModule {
}

我的CategoriesService 是:

@Injectable()
export class CategoriesService {
    constructor(@InjectModel(Category.name) private categoryModel: Model<CategoryDocument>) {
    }

    ...
}

然后我有一个该服务的开玩笑测试文件categories.service.spec.ts

describe('CategoriesService', () => {
    let service: CategoriesService

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            providers: [CategoriesService]
        }).compile()

        service = module.get<CategoriesService>(CategoriesService)
    })

    it('should be defined', () => {
        expect(service).toBeDefined()
    })
})

但是当我运行测试时(使用脚本test 内置的nestJs)如果失败并出现此错误:

Nest can't resolve dependencies of the CategoriesService (?). Please make sure that the argument CategoryModel at index [0] is available in the RootTestModule context.

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

但我不明白,当使用npm start 运行服务器时,一切正常, 在这里它抱怨CategoryModel,为什么?

【问题讨论】:

    标签: node.js jestjs nestjs


    【解决方案1】:

    类别模型在CategoryService 中使用,因此是CategoryService 的依赖项。您需要将模型添加到您的规范文件中,以便解决依赖关系。 如果您使用猫鼬,请查看this answer,它会对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-05-07
      • 2020-09-21
      • 2020-11-16
      • 1970-01-01
      • 2021-02-22
      • 2021-10-15
      • 2019-10-21
      • 1970-01-01
      • 2022-11-09
      相关资源
      最近更新 更多