Unit testing 具有服务依赖性的Angular2组件单元测试
因此,我有这个PromptComponent,内容将由服务数据更新。 现在我尝试对这个具有服务依赖性的组件进行单元测试。 以下是组件:Unit testing 具有服务依赖性的Angular2组件单元测试,unit-testing,angular,service,dependency-injection,jasmine,Unit Testing,Angular,Service,Dependency Injection,Jasmine,因此,我有这个PromptComponent,内容将由服务数据更新。 现在我尝试对这个具有服务依赖性的组件进行单元测试。 以下是组件: export class PromptComponent { @Input() module: any; @select() selectedPrompt; constructor(private moduleService: ModuleService){} } 服务内容如下: getQuote(): Promise<str
export class PromptComponent {
@Input() module: any;
@select() selectedPrompt;
constructor(private moduleService: ModuleService){}
}
服务内容如下:
getQuote(): Promise<string> {
return new Promise(resolve => {
setTimeout( () => resolve(this.nextQuote()), 500 );
});
}
private nextQuote() {
if (this.next === quotes.length) { this.next = 0; }
return quotes[ this.next++ ];
}
我参考了angular文档的官方演示
,如TwainComponent.spec中所示
真正奇怪的是,正如预期的那样,在官方演示中,TwainComponent测试顺利通过。但另一方面,我得到了一个奇怪的注射错误。如果我删除构造函数中的参数,我就能够创建fixture实例,但是当它在injector.get()部分上运行时会出现注入错误。但只要我将私有模块服务:模块服务
放回组件构造函数中,我就会得到未定义的fixture,并且还有注入错误
这意味着我甚至无法对实际的服务注入部分执行代码(fixture.debugElement.injector.get(ModuleService)
),我已经得到了错误
有人有同样的问题吗?
我的代码与Plunker上的演示代码几乎相同。不知道如何前进……您的服务是否用
@Injectable()
注释进行了注释?尝试添加异步,如:beforeach(异步(()=>{…您的服务是否用@Injectable()
注释进行了注释?尝试添加异步,如:beforeach(异步(()=>{。。。
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
PromptComponent,
],
providers: [ ModuleService]
});
fixture = TestBed.createComponent(PromptComponent);
component = fixture.componentInstance;
const moduleService = fixture.debugElement.injector.get(ModuleService);
spy = spyOn(moduleService, 'getQuote').and.returnValue(Promise.resolve(testService));