我想在 mall.service.spec.ts 中测试我的商城服务 请帮忙解释为什么 npm 不起作用。
// mall.service.spec.ts
describe('MallService', () => {
let service: MallService
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [TypeOrmModule.forFeature([User, TestRepository])],
controllers: [MallController],
providers: [
MallService,
{
provide: IUSER_REPOSITORY,
useClass: TestRepository,
},
],
}).compile()
service = module.get<MallService>(MallService)
})
it('should be defined', () => {
expect(service).toBeDefined()
})
})
// mall.service.ts
@Injectable()
export class MallService {
constructor(
@Inject(IUSER_REPOSITORY)
private readonly userRepository: IUserRepository,
) {}
...
}
模块设置有什么问题? 当我运行测试时,它会显示如下所示。
- Nest can't resolve dependencies of the MallController (?). Please
make sure that the argument MallService at index [0] is available in
the RootTestModule context.
Potential solutions:
- Is RootTestModule a valid NestJS module?
- If MallService is a provider, is it part of the current RootTestModule?
- If MallService is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing MallService */ ]
})*
请帮忙,谢谢。 请帮忙,谢谢。 请帮忙,谢谢。
我相信你必须覆盖提供者,如下所示。 更多内容可以阅读NestJS 文档
// mall.service.spec.ts
describe('MallService', () => {
let service: MallService
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [TypeOrmModule.forFeature([User, TestRepository])],
controllers: [MallController],
providers: [
MallService,
IUSER_REPOSITORY,
],
}).overrideProvider(IUSER_REPOSITORY)
.useValue(TestRepository)
.compile()
service = module.get<MallService>(MallService)
})
it('should be defined', () => {
expect(service).toBeDefined()
})
})