我在一个Angular2组件的ngOnInit方法中运行http调用(使用obervable):
ngOnInit() {
this.descriptorService.generateDescriptors(new Server());
this.fetchData();
}
fetchData () {
console.log('Starting Http call');
this.dataService.listAll(Server).subscribe(
servers=>{console.log('Http Call done');this.listServers=servers},
error=>console.log(error)
);
}
使用以下dataService.listAll():
listAll(zeClass:typeof Model): Observable<T[]> {
console.log('Http call begin');
return this.http.get(this.calculateUrl(zeClass))
.map(this.extractData)
.map((jsonArray)=>{
let data:Array<ModelInterface>=new Array<ModelInterface>();
if (isArray (jsonArray)) {
console.log('Http call in');
...
return data;
})
.catch(this.handleError);
}
当我为这个组件运行以下单元测试时(http用InMemoryWebApiModule进行模拟):
it('should display the list of servers', async(() => {
fixture.detectChanges();
console.log('Before whenStable():'+fixture.isStable());
fixture.whenStable().then(()=>{
console.log('In whenStable()');
fixture.detectChanges();
let de:Array<DebugElement> = fixture.debugElement.queryAll(By.css('md-list-item'));
expect(de.length).toBeGreaterThan(1);
});
console.log('After whenStable():'+fixture.isStable());
}));
然后我在控制台中获得以下日志:
LOG: 'Starting Http call'
LOG: 'Http call begin'
LOG: 'Before whenStable():false'
LOG: 'After whenStable():false'
你可以在什么时候运行什么时候看到测试代码... 为什么?
答案 0 :(得分:3)
感谢@jonrsharpe指出我正确的方向。 实际上,我必须使用Jasmine和间谍。
有关信息,请参阅以下工作测试代码:
beforeEach(inject([GenericDataService], (dataService) => {
spy = spyOn(dataService,'listAll').and.callThrough();
...
}
和
it('should display the list of servers', done => {
fixture.detectChanges();
spy.calls.mostRecent().returnValue.subscribe (() => {
console.log('In spy()');
fixture.detectChanges();
let de:Array<DebugElement> = fixture.debugElement.queryAll(By.css('md-list-item'));
expect(de.length).toBeGreaterThan(1);
done();
});
});