【发布时间】:2017-04-12 15:38:07
【问题描述】:
我尝试使用 Jasmine 和 Karma 测试组件,但是当我想测试我的服务是否已在 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”的错误实现(它没有返回我需要的东西),但我不知道如何改变它。
感谢您的帮助!
【问题讨论】:
标签: unit-testing angular jasmine