【发布时间】: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,为什么?
【问题讨论】: