使用Jest运行测试时,NestJs无法编译测试模块



我有一个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>) {
}
...
}

然后我有该服务的jest测试文件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,为什么?

类别模型在CategoryService中使用,因此是CategoryService的依赖项。您需要将模型添加到您的规范文件中,以便解决依赖关系。如果你正在使用猫鼬,看看这个答案,它会帮助你。

最新更新