我有一个 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()
})
})
但是当我运行测试时(使用 nestJs 内置脚本 test
)如果失败并出现此错误:
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
,为什么?
答案 0 :(得分:1)
类别模型在 CategoryService
中使用,因此是 CategoryService
的依赖项。您需要将模型添加到规范文件中,以便解决依赖关系。
如果您使用的是猫鼬,请查看 this answer,它会对您有所帮助。