2
我嘗試使用茉莉花測試一個組件&噶,但是當我想測試我的服務是否已在ngOnInit()中調用時出現錯誤我不明白:單元測試 - 服務在ngOnInit:錯誤'地圖不是函數'
Failed: Uncaught (in promise): TypeError: tagelers.map is not a function
TypeError: tagelers.map is not a function
at tagelerService.getTagelers.then (http://localhost:9876/base/src/test.ts?779e448059ef6555f776fac9a62a71930cc82ee7:68007:38)
....
我的組件看起來是這樣的:
import ..
@Component({
selector: 'app-group-details',
templateUrl: 'group-details.component.html',
styleUrls: ['group-details.component.css'],
})
export class GroupDetailsComponent implements OnInit {
@Input()
tageler: Tageler;
tagelers: Tageler[];
group: Group;
constructor(
private route: ActivatedRoute,
private groupService: GroupService,
private tagelerService: TagelerService) {
}
ngOnInit() {
console.log("Init Details");
this.route.params
.switchMap((params: Params) => this.groupService.getGroup(params['id']))
.subscribe(group => this.group = group);
this.tagelerService
.getTagelers()
.then((tagelers: Tageler[]) => {
this.tagelers = tagelers.map((tageler) => {
if (!tageler.title) {
tageler.title = 'default';
}
return tageler;
});
});
}
}
這是該方法看起來像在tagelerService:
getTagelers(): Promise<Tageler[]> {
return this.http.get(this.tagelersUrlGet)
.toPromise()
.then(response => response.json() as Tageler[])
.catch(this.handleError);
}
這我的測試是我spec.ts文件失敗:
it('should get tagelers when ngOnInit is called', async(() => {
spyOn(tagelerService, 'getTagelers').and.returnValue(Promise.resolve(Tageler));
component.ngOnInit();
fixture.detectChanges();
expect(tagelerService.getTagelers).toHaveBeenCalled();
}));
有誰知道爲什麼有一個「.MAP不是一個函數」的錯誤?我猜這個問題是'spyOn'的錯誤實現(它不會返回我所需要的),但我不知道如何改變它。
感謝您的幫助!
謝謝,這工作! – Ramona