Ken*_*nny 5 unit-testing jasmine karma-jasmine angular
我遇到了一个尝试监视构造函数中被调用的服务函数调用的问题。该测试是基本的,只需验证该函数调用实际上已被调用即可。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
providers: [TestService]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
let service = fixture.debugElement.injector.get(TestService);
component = fixture.componentInstance;
spyOn(service , "start").and.callThrough();
fixture.detectChanges();
});
it('start gets called', () => {
expect(service .start).toHaveBeenCalled();
})
Run Code Online (Sandbox Code Playgroud)
至于AppComponent,在构造函数中只是调用service.start()我认为问题在于,在创建组件之后会调用spyOn,但是在注入之前如何监视服务?即:
fixture = TestBed.createComponent(AppComponent);
let service = fixture.debugElement.injector.get(TestService);
Run Code Online (Sandbox Code Playgroud)
在我看来,当您设置间谍时,组件的构造函数已被调用,因此需要稍微更改顺序。
beforeEach(() => {
let service = TestBed.get(TestService);
spyOn(service , "start").and.callThrough();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
Run Code Online (Sandbox Code Playgroud)
参考角测试台
| 归档时间: |
|
| 查看次数: |
4655 次 |
| 最近记录: |