我正在启动一个 Angular 5 项目,它会自动为我的组件和服务生成一些规范单元测试。对于那些需要 Apollo 的组件,我收到错误 NullInjectorError: No provider for Apollo!
我将 Apollo 模块添加到导入和声明部分,如下所示:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ContractsDashboardComponent, Apollo ]
})
.compileComponents();
}));
但是现在我得到了错误
失败:模块“DynamicTestModule”声明的意外值“Apollo”。请添加@Pipe/@Directive/@Component 注解。
在普通应用程序中,我有一个模块 GraphQLModule
,它在构造函数中调用 apollo.create
。我是否也应该以某种方式 mock 它?
最佳答案
如果 Apollo 是一个模块,那么你应该导入它。
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ Apollo ],
declarations: [ ContractsDashboardComponent ]
})
.compileComponents();
}));
如果它不是一个模块,它应该是一个提供者,所以你需要提供它:
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [ Apollo ],
declarations: [ ContractsDashboardComponent ]
})
.compileComponents();
}));
因为很明显,它不是一个组件(错误要求它有一个组件装饰器),但您将其放入声明中。
由于您的第一个错误是 NullInjectorError: No provider for Apollo!
,我猜想 Apollo 是您注入(inject)到组件中的服务,因此您应该使用第二种方法,即提供。
关于angular - 如何使用 Apollo 和 Angular 创建单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187505/